我什么时候需要使用 hasOwnProperty()? [英] When do I need to use hasOwnProperty()?

查看:63
本文介绍了我什么时候需要使用 hasOwnProperty()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want.

但这总是需要的吗?是否存在不需要它的情况?局部变量也需要这个吗?

But is this always required? Are there situations where it's not needed? Is this required for local variables too?

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

我只是不喜欢在循环中添加额外的if,如果我不需要的话.

I just don't like adding an extra if inside the loop if I don't have to.

拥有财产的死亡

这家伙说我不应该再使用它了.

This guy says I shouldn't use it at all any more.

推荐答案

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

Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.

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

In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.

例如:

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

如果您只想拥有自己的财产,是否要避免整个检查?

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

Do you want to avoid the whole check if you want own properties only?

Since ECMAScript 5.x, Object has a new function Object.keys which returns an array of strings where its items are the own properties from a given object:

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 循环:

Also, since ECMAScript 5.x, Array.prototype has Array.prototype.forEach which let’s perform a for-each loop fluently:

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
});

这篇关于我什么时候需要使用 hasOwnProperty()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆