Iterate over String.prototype

混江龙づ霸主 提交于 2019-12-10 15:27:15

问题


I am aware that the for in loop can help iterate through properties of objects, prototypes and collections.

The fact is, I need to iterate over String.prototype, and though console.log(String.prototype) displays the complete prototype, when I do

for (var prop in String.prototype) {
    console.log(prop);
}

to display the name of the elements in the prototype, it displays nothing, as if it were empty.

Do the JavaScript engines hide the basic prototypes methods, or am I doing something wrong?


回答1:


The specification says:

If the value of an attribute is not explicitly specified by this specification for a named property, the default value defined in Table 7 is used.

Table 7 — Default Attribute Values

...

[[Enumerable]] false

So it is not enumerable (as with all built-in properties).




回答2:


Like others have said, all properties in String.prototype are non-enumerable. To get a list of all the properties, including non-enumerable, use Object.getOwnPropertyNames() (newer browsers only)




回答3:


Native methods aren't visible through an for(prop in obj) iteration.

It's possible to find properties when you loop through a built-in object. In this case, the page has extended the prototype with a custom method. Frameworks (such as jQuery) often modify built-in objects in this way.



来源:https://stackoverflow.com/questions/7770869/iterate-over-string-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!