gpt4 book ai didi

javascript - 我什么时候需要使用 hasOwnProperty()?

转载 作者:可可西里 更新时间:2023-11-01 01:37:27 25 4
gpt4 key购买 nike

我读到在循环对象时我们应该始终使用 hasOwnProperty,因为对象可以被其他东西修改以包含一些我们不想要的键。

但这总是必需的吗?有没有不需要的情况?这对局部变量也是必需的吗?

function my(){
var obj = { ... };
for(var key in obj){
if(obj.hasOwnProperty(key)){
safe
}
}
}

我只是不喜欢在不必要的情况下在循环中添加额外的 if

Death to hasOwnProperty

这家伙说我根本不应该再使用它了。

最佳答案

Object.hasOwnProperty 确定整个属性是在对象本身还是在原型(prototype)链中定义。

换句话说:如果您希望属性(带有数据或函数)来自对象本身以外的其他地方,则进行所谓的检查。

例如:

function A() {
this.x = "I'm an own property";
}

A.prototype.y = "I'm not an own property";

var instance = new A();
var xIsOwnProperty = instance.hasOwnProperty("x"); // true
var yIsOwnProperty = instance.hasOwnProperty("y"); // false

如果你只想要自己的属性(property),你想避免整个检查吗?

从 ECMAScript 5.x 开始,Object 有一个新函数 Object.keys,它返回一个字符串数组,其中的项目是给定的自己的属性对象:

var instance = new A();
// This won't contain "y" since it's in the prototype, so
// it's not an "own object property"
var ownPropertyNames = Object.keys(instance);

此外,自 ECMAScript 5.x 以来,Array.prototype 具有 Array.prototype.forEach,让我们可以流畅地执行 for-each 循环 :

Object.keys(instance).forEach(function(ownPropertyName) {
// This function will be called for each found "own property", and
// you don't need to do the instance.hasOwnProperty check any more
});

关于javascript - 我什么时候需要使用 hasOwnProperty()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422867/

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