Javascript hasOwnProperty vs Property可枚举

Javascript hasOwnProperty vs Property可枚举,javascript,prototype,Javascript,Prototype,有谁能告诉我,两者的区别是什么 hasOwnProperty和propertyEnumerable: 函数f(){ 这是a=1; 这是b=2; this.c=函数(){} } f、 原型={ d:3, e:4, g:函数(){} } //创建对象的实例: var o=新的f(); //在这里我看不出有什么不同。 //在我看来,他们正在做同样的事情 log(“o.hasOwnProperty('a'):”,o.hasOwnProperty('a'))//真的 log(“o.hasOwnPrope

有谁能告诉我,两者的区别是什么
hasOwnProperty
propertyEnumerable

函数f(){
这是a=1;
这是b=2;
this.c=函数(){}
}
f、 原型={
d:3,
e:4,
g:函数(){}
}
//创建对象的实例:
var o=新的f();
//在这里我看不出有什么不同。
//在我看来,他们正在做同样的事情
log(“o.hasOwnProperty('a'):”,o.hasOwnProperty('a'))//真的
log(“o.hasOwnProperty('b'):”,o.hasOwnProperty('b'))//真的
log(“o.hasOwnProperty('c'):”,o.hasOwnProperty('c'))//真的
log(“o.hasOwnProperty('d'):”,o.hasOwnProperty('d'))//假的
log(“o.hasOwnProperty('e'):”,o.hasOwnProperty('e'))//假的
log(“o.hasOwnProperty('g'):”,o.hasOwnProperty('g'))//假的
log(“o.propertyIsEnumerable('a')”,o.propertyIsEnumerable('a'))//真的
log(“o.propertyEnumerable('b')”,o.propertyEnumerable('b'))//真的
log(“o.propertyEnumerable('c')”,o.propertyEnumerable('c')//真的
log(“o.propertyEnumerable('d')”,o.propertyEnumerable('d')//假的
log(“o.propertyEnumerable('e')”,o.propertyEnumerable('e'))//假的
log(“o.propertyEnumerable('g')”,o.propertyEnumerable('g'))//false
对于“hasOwnProperty”,函数“propertyIsEnumerable”始终排除不会返回
true
的属性。您没有做任何事情使任何属性不可枚举,因此在测试中结果是相同的

您可以使用“defineProperty”来定义不可枚举的属性;在MDN

这就像:

obj.hideMe = null;
除了属性不会显示在。。。在循环中,使用
propertyEnumerable
的测试将返回
false


整个主题都是关于旧浏览器中不可用的功能,如果这些功能不明显的话。

区别在于,propertyIsEnumerable仅在属性存在时返回true,如果可以对属性执行ForIn,hasOwnProperty将在属性存在时返回true,而不考虑ForIn支持

从MSDN:

如果proName在中存在,propertyIsEnumerable方法返回true 对象,并可以使用ForIn循环枚举。这个 如果对象没有可枚举的属性,则propertyIsEnumerable方法返回false 属性,或者如果指定的属性不是 可枚举的。通常,预定义属性在运行时不可枚举 用户定义的属性始终是可枚举的

如果对象具有 指定的名称,如果未指定,则为false。此方法不检查 属性存在于对象的原型链中;财产必须 成为对象本身的成员

即使对于不可枚举的“own”属性(如
数组中的
长度
),也将返回
true
。将仅针对可枚举的“自有”属性返回
true
。(可枚举属性是在等中显示的属性。)

例如:

var a=[];
console.log(a.hasOwnProperty('length'));//“对”
console.log(a.propertyEnumerable('length'));//“false”
简单地说:

hasOwnProperty
仅当属性是对象的属性且未继承时才会返回true。这个很简单

propertyEnumerable
将返回true当且仅当
hasOwnProperty
返回true且属性可枚举时。因此,
propertyEnumerable
是在
hasOwnProperty
测试之上的一个“附加要求”,如果名称
propertyEnumerable
hasOwnProperty且不可计算的,那么它将更加准确


演示:

此解释比公认的答案更清晰。感谢您提供的简明摘要!所以,当我想要特别严格时,我将使用propertyIsEnumerable–那时不需要hasOwnProperty。我一直看到在过滤“key in obj”循环时经常使用“hasOwnProperty”,但很少使用“propertyIsEnumerable”……所以对于for in循环变量来说,这没有什么区别,它们的行为完全相同?@BobStein<代码>for(让输入obj)
将跳过现有但不可枚举的属性。它还将包括属性链中的属性
obj.hideMe = null;