谁能告诉我,hasOwnProperty和propertyIsEnumerable的区别是什么?
function f(){
this.a = 1;
this.b = 2;
this.c = function(){}
}
f.prototype = {
d : 3,
e : 4,
g : function(){}
}
//creating the instance of an object:
var o = new f();
//And here I can't see difference.
//In my opinion they are doing the same thing
console.log("o.hasOwnProperty('a'):", o.hasOwnProperty('a')); //true
console.log("o.hasOwnProperty('b'):", o.hasOwnProperty('b')); //true
console.log("o.hasOwnProperty('c'):", o.hasOwnProperty('c')); //true
console.log("o.hasOwnProperty('d'):", o.hasOwnProperty('d')); //false
console.log("o.hasOwnProperty('e'):", o.hasOwnProperty('e')); //false
console.log("o.hasOwnProperty('g'):", o.hasOwnProperty('g')); //false
console.log("o.propertyIsEnumerable('a')", o.propertyIsEnumerable('a')); //true
console.log("o.propertyIsEnumerable('b')", o.propertyIsEnumerable('b')); //true
console.log("o.propertyIsEnumerable('c')", o.propertyIsEnumerable('c')); //true
console.log("o.propertyIsEnumerable('d')", o.propertyIsEnumerable('d')); //false
console.log("o.propertyIsEnumerable('e')", o.propertyIsEnumerable('e')); //false
console.log("o.propertyIsEnumerable('g')", o.propertyIsEnumerable('g')); //false
如果我错了,请纠正我
发布于 2012-06-10 21:10:17
"propertyIsEnumerable“函数总是排除那些不会为"hasOwnProperty”返回true的属性。您没有做任何事情来使任何属性不可枚举,因此在测试中结果是相同的。
您可以使用"defineProperty“来定义属性,这些属性是而不是 enumerable;see this reference at MDN。
Object.defineProperty(obj, "hideMe", { value: null, enumerable: false });这就像:
obj.hideMe = null;除了该属性不会出现在for ... in循环中,并且使用propertyIsEnumerable进行测试将返回false。
这整个主题是关于旧浏览器中没有的功能,如果这不是显而易见的话。
发布于 2012-06-10 21:22:29
即使对于不可枚举的"own“属性(就像Array中的length ),hasOwnProperty也会返回true。propertyIsEnumerable将只为可枚举的"own“属性返回true。( "enumerable“属性是在for..in loops之类的地方显示的属性。)
示例:
var a = [];
console.log(a.hasOwnProperty('length')); // "true"
console.log(a.propertyIsEnumerable('length')); // "false"
或者使用非数组对象:
var o = {};
Object.defineProperty(o, "foo", { enumerable: false });
console.log(o.hasOwnProperty('foo')); // "true"
console.log(o.propertyIsEnumerable('foo')); // "false"
(当您使用Object.defineProperty时,enumerable默认为false,但为了清楚起见,我在上面已经明确说明了。)
发布于 2013-07-06 09:26:11
简单地说:
当且仅当该属性是对象的属性且不是继承的时,
hasOwnProperty才会返回true。这个很简单。
和
当且仅当hasOwnProperty返回true并且该属性是可枚举的时,
propertyIsEnumerable才会返回true。因此,propertyIsEnumerable是hasOwnProperty测试之上的一个“附加要求”,如果名称为hasOwnPropertyAndIsEnumerable,那么propertyIsEnumerable这个名称会更准确。
演示:http://jsfiddle.net/aby3k/
https://stackoverflow.com/questions/10968962
复制相似问题