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

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

hasOwnProperty死亡

这个人说我不应该再使用它了.

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天全站免登陆