我们知道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/