javascript - for..in 循环和 Object.keys 不同的行为

标签 javascript

我有这个对象函数构造函数:

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/

相关文章:

javascript - AngularJS 指令将 n 个元素的数组呈现为每个 m 行的表

javascript - 用 POST 替换 GET

javascript - 无法在 Azure 中使用 Javascript 方法

javascript - 捕获 child_process spawnSync 或 execSync stdout

javascript - React-redux connect HOC 作为类装饰器,@connect

javascript - 如果没有 setTimeOut,MatSort 和 MatPaginator 将无法工作

javascript - 在输入中输入一个值“内部名称”?

javascript - 为什么 Twitter Typeahead 不适用于 React js?

javascript - 将动态参数添加到函数,该函数的参数作为参数传递给当前函数

javascript - Firefox 扩展 : File Read/Write using OS. File.jsm