我有这个对象函数构造函数:
const Shape = function(name){
this.name = name;
}
Shape.prototype.getName = function(){
return this.name;
};
我有这个实例
const square = new Shape("square");
当我使用 for 循环迭代方形对象时,我可以看到迭代过程正在方形对象的原型(prototype)上发生
for (const key in square) console.log(key);
/* #output:
name
getName
*/
但是当我使用 Object.keys() 函数时,我可以看到迭代过程没有迭代原型(prototype)对象
/* #output:
["name"]
*/
背后的原因是什么?
这是我尝试过的:
我已经尝试从原型(prototype)对象中 console.log getName 方法的描述符,我看到 enumerable 属性默认设置为 true:
console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(square), "getName"))
/* #output:
configurable: true
enumerable: true
value: ƒ ()
writable: true
__proto__: Object
*/
最佳答案
Object.keys
仅迭代可枚举的自身 属性。相反,for..in
遍历对象原型(prototype)链上任何位置的所有可枚举属性。
使用这段代码:
const Shape = function(name){
this.name = name;
}
Shape.prototype.getName = function(){
return this.name;
};
Shape
实例正在接收一个 name
的自有属性,因此它会被两种迭代方法迭代。相反,getName
在实例的原型(prototype) 上 - 它不是实例本身的属性,因此它不会在 Object.keys
中返回:
const Shape = function(name){
this.name = name;
}
Shape.prototype.getName = function(){
return this.name;
};
const square = new Shape("square");
console.log(
square.hasOwnProperty('name'),
square.hasOwnProperty('getName'),
Shape.prototype.hasOwnProperty('getName')
);
关于javascript - for..in 循环和 Object.keys 不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63780107/