Why are the properties of the native data type not shown on their respective prototypes?

For example, the Array data type has a function called pop() , which I suppose is added with:

 Array.prototype.pop = function(){ /* ... */ }; 

But as far as I know, the only way to make it non-enumerable is to do something like this:

 Object.defineProperty(Array.prototype, "pop", { enumerable: false }); 

Which is not supported by all browsers.

 Array.prototype.doSomething= function(){ }; var arr = []; console.log(arr); // [doSomething: function] 

So why doSomething appears here and pop() doesn't? Are they both added to the prototype?

+6
source share
1 answer

MDN says:

A for ... in loop does not iterate over enumerable properties. Objects created from built-in constructors such as Array and Object inherit non-enumerable properties from Object.prototype and String.prototype, which are not enumerable, such as the String indexOf or Object toString method. The cycle will iterate over all the enumerable properties of the object itself and those objects that its prototype constructor inherits (properties close to the object in the prototype properties override prototype properties).

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in

What is being logged presumably comes from an iteration of for..in.. or similar.

The notion of non-enumerable properties precedes the function of specifying the enumerability of properties directly in Javascript.

MDN says:

ECMAScript 3 has an internal DontEnum attribute. This attribute is bound by default to certain properties (ยง8.6.1).

The internal DontEnum attribute defines what should not be enumerated by enumeration for-in (ยง12.6.4). propertyIsEnumerable Test

https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute

The EcmaScript 3 specification defines many properties with the DontEnum attribute. http://bclary.com/2004/11/07/

This does not actually solve the whole puzzle, because, for example, Array.prototype.pop is not explicitly specified as having the DontEnum attribute, only Array.prototype itself Array.prototype specified. It is possible that the DontEnum attribute of the built-in functions is implied, but I cannot find a link for this. The first quote from MDN, for example, describes String.prototype.indexOf as non-enumerable, while this is not explicitly mentioned in the EcmaScript 3 specification.

+4
source

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


All Articles