javascript - for...in 循环和原型(prototype)链

标签 javascript

我们知道for..in循环不关心属性是否是对象原型(prototype)链的属性,所以它会输出属性all。 让我们做一个测试

var o={};
for(var i in o){
    console.log(o[i]);//  output  none
}

一个对象(通过这种方式创建:{})来自对象,
但是当我们运行代码时,对象原型(prototype)链方法(如 toString )没有输出
为什么Object的原型(prototype)链中的方法(toString)没有输出????

最佳答案

toString 不是 enumerable :

("toString" in {}) === true
({}).propertyIsEnumerable("toString") === false

您可以像这样创建自己的不可枚举属性:

var object = {};

Object.defineProperty(object, "property", { enumerable: false, value: 5 });

从技术上讲,您可以省略 enumerable: false,因为这是默认值。


这表示in the spec在总括第 15 条中:

In every case, the length property of a built-in Function object described in this clause has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }. Every other property described in this clause has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true } unless otherwise specified.

关于javascript - for...in 循环和原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10099374/

相关文章:

javascript - 视网膜图像显示

javascript - 在滚动 div 中保留 x 行数

java - 如何获取完全加载页面的 html(使用 javascript)作为 java 中的输入?

javascript - 根据元标题隐藏元素

c# - 如何在不在 JavaScript 中定义类的情况下创建类?

javascript - jQuery 获取错误数据

javascript - 替换 WordPress 插件中硬编码的 JavaScript 字符串

javascript - 将传单缩放级别与 d3 地理比例相匹配

javascript - WordPress : Post Content Need in the bootstrap modals without repeating the model in loop

javascript - 使用 jquery 更改多个图像大小