gpt4 book ai didi

javascript - hasOwnProperty 与 propertyIsEnumerable

转载 作者:行者123 更新时间:2023-12-03 03:29:50 24 4
gpt4 key购买 nike

谁能告诉我,两者有什么区别hasOwnPropertypropertyIsEnumerable:

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

如果我错了请纠正

最佳答案

“propertyIsEnumerable”函数始终排除不会为“hasOwnProperty”返回 true 的属性。您没有采取任何措施使任何属性不可枚举,因此在您的测试中结果是相同的。

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

Object.defineProperty(obj, "hideMe", { value: null, enumerable: false });

就像:

obj.hideMe = null;

除非该属性不会显示在 for ... in 循环中,并且使用 propertyIsEnumerable 进行测试将返回 false

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com