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

查看:287
本文介绍了我什么时候需要使用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
    }

  }
}

如果我不喜欢,我只是不喜欢在循环中加一个额外的t必须。

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

http:// phrogz。 net / death-to-hasownproperty

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

This guy says I shouldn't use it all anymore.

推荐答案

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



如果只想要自己的属性,是否要避免全部检查?



由于ECMA-Script 5.x, Object 有一个新函数 Object.keys 返回一个字符串数组,其中的项是来自给定对象的自己的属性

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

Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string 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);

此外,由于ECMA-Script 5.x, Array.prototype Array.prototype.forEach ,它允许流利地执行 for-each循环

Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets 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 anymore
});

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

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