为什么这个属性在一个实例中打印,而不是在类似的实例中打印,即使它在两个实例中都是可枚举的

Why is this property printed in one instance and not in a similiar one even though it is enumerable in both?

本文关键字:实例 打印 两个 枚举 属性 一个 为什么      更新时间:2023-09-26

在接下来的代码中(这是一个后续问题,但与那个无关),我基本上是将函数分配给对象的属性。函数本身实际上打印对象中所有属性的键。

function print(item) {
  console.log(item);
}
var hello = {
  10: 100,
  20: 200,
  30: 300,
  40: 400,
  50: 500
};
hello.print = function () {
  Object.keys(hello).map(print, this);
};
hello.print();

在上面的实例中,函数像预期的那样打印自己的键。http://jsbin.com/bujutefa/1/edit

但是,在下面的场景中,它没有。

hello.print = Array.prototype.map.bind(Object.keys(hello), print, hello);
hello.print();
http://jsbin.com/fezedara/1/edit

我不明白为什么这两种情况不同。我已经检查了print是否是可枚举的。

好的,我知道了。

在第一个场景中,在调用函数时计算Object.keys(),因此也包括print

在第二个场景中,右边的表达式在函数被自然调用之前求值,因此结果函数已经绑定到Object.keys()的数组,就像它在求值和赋值完成之前一样。因此,即使当函数被调用时,print是一个可枚举的属性,它也不会被打印出来,因为正在被调用的函数在执行过程中绑定了一个由Object.keys()返回的数组,而print还不是一个属性,因此不包括print