简体   繁体   English

迭代String.prototype

[英]Iterate over String.prototype

I am aware that the for in loop can help iterate through properties of objects, prototypes and collections. 我知道for in循环可以帮助迭代对象,原型和集合的属性。

The fact is, I need to iterate over String.prototype , and though console.log(String.prototype) displays the complete prototype, when I do 事实是,我需要迭代String.prototype ,虽然console.log(String.prototype)显示完整的原型,当我这样做

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? JavaScript引擎是否隐藏了基本的原型方法,或者我做错了什么?

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. 如果此规范未为命名属性显式指定属性的值,则使用表7中定义的默认值。

Table 7 — Default Attribute Values 表7 - 默认属性值

... ...

[[Enumerable]] false [[可枚举]]假

So it is not enumerable (as with all built-in properties). 所以它不是可枚举的(与所有内置属性一样)。

Like others have said, all properties in String.prototype are non-enumerable. 像其他人所说的那样,String.prototype中的所有属性都是不可枚举的。 To get a list of all the properties, including non-enumerable, use Object.getOwnPropertyNames() (newer browsers only) 要获取所有属性的列表,包括非枚举,请使用Object.getOwnPropertyNames() (仅限较新的浏览器)

Native methods aren't visible through an for(prop in obj) iteration. 通过for(prop in obj)迭代不可见本机方法。

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. 框架(例如jQuery)通常以这种方式修改内置对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM