Why does the value of the array length property change even when it is set as read-only in javascript?

I tried the following code in the Chrome console

var a = new Array(1,2,3,4); a.length 

This shows the length as 4 as expected. Now I tried setting the length property as writable: false

 Object.defineProperty(a, "length", {writable: false}); a[4] = 5; a.length 

The result is 5, even if the property is set to write: false. How did this happen? Should it stay the same as it is read-only (writable: false)?

+6
source share
3 answers

The writable property restricts the use of assignment operators to this property. . In addition, the value of the writable property is already false by default .

For instance:

 var a = new Array(1,2,3,4); a.length; # 4 a.length++; # a.length is still 4 

You can see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

If you want to keep the original value of a.length , I think you better assign it to another variable:

 x = [1,2,3,4]; # x.length is 4 y = x.length; # y is 4 x = [1,2,3,4,5] # x.length is now 5, but y is still 4 
+2
source

Object.defineProperty(a, "length", {writable: false}); only affects how you assign a value directly to the .length property.

 var a = [1,2,3,4]; Object.defineProperty(a, "length", {writable: false}); a.length = 0; console.log(a.length); // still be 4 
+5
source

It also depends on what the length property actually returns. See the following example.

 var MyObject = function(){ var _count = 0; this.increment = function(){ _count++; } this.getCount = function(){ return _count; } }; var object = new MyObject(); Object.defineProperty(object, "count", { // new property `count` calls `getCount` writeable:false, get: function(){ return this.getCount(); } }); alert(object.count); // 0 object.count = 90; object.increment(); alert(object.count); // 1 object.count = 100; object.increment(); alert(object.count); //2 

Creating a read-only property means you cannot assign a value to it. At the same time, it does not change what the property returns when it is read. It depends on the internal definition of this property.

0
source

Source: https://habr.com/ru/post/946661/


All Articles