我在 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/