javascript - propertyIsEnumerable(x) 与 x in

标签 javascript properties enumeration enumerable

我在 Javascript 代码中遇到了 o.propertyIsEnumerable(x) 方法。我将其理解为 x in o 构造的同义词。有区别吗?如果是这样,您能否在一些实际示例中说明何时使用第一个结构以及何时使用第二个结构?

var o = {};
o.x = 1;
o.y = 2;

if ("x" in o) {
 // some code
}

if (o.propertyIsEnumerable(x)) {
  // some code
}

最佳答案

解决此类问题的最简单方法是遵循规范中的算法。这就是它告诉我们关于 propertyIsEnumerable 的内容:

  • Let desc be the result of calling the [[GetOwnProperty]] internal method of O passing P as the argument.

  • If desc is undefined, return false.

  • Return the value of desc.[[Enumerable]].

如您所见,它将调用 [[GetOwnProperty]] internal method所讨论的对象。这只是从对象本身(而不是从它的原型(prototype)链中的任何东西)返回指定属性的值。

现在让我们看看 in operator :

Return the result of calling the [[HasProperty]] internal method of rval with argument ToString(lval).

如果您查看 [[HasProperty]] internal method :

Let desc be the result of calling the [[GetProperty]] internal method of O with property name P

在这里你可以看到不同之处。 in 运算符导致使用 [[[GetProperty]] 内部方法][4],而不是 [[GetOwnProperty]] 方法,这意味着它将在原型(prototype)链下查找对象的属性。

另一个主要区别是您可以在对象上定义不可枚举的属性(使用 Object.defineProperty 方法)。如果您定义了一个不可枚举的属性,它in 运算符返回,但显然不是由propertyIsEnumerable 方法返回。这是一个 fiddle that demonstrates the difference .

关于javascript - propertyIsEnumerable(x) 与 x in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728728/

相关文章:

javascript - fancybox inline 显示无法加载请求的内容。请稍后再试

javascript - javascript中的整数长度

c# - 将 UserControl 属性设置为不显示在 VS 属性窗口中

javascript - 虽然不能保证 for..in 循环中的元素顺序,但在实践中实现之间有什么偏差?

c# - 有序枚举

javascript - 允许 div 仅垂直增长 x 个像素然后显示滚动条?

javascript - HighCharts:动态设置一列的特定边框宽度和边框颜色

javascript - 用户点击 "open link in new tab"时调用函数

Java : Where exactly the Properties would be configured?

objective-c - 目标 - C - << 在枚举中的使用