简体   繁体   English

在检查属性是否作为对象文字的一部分存在时,HasOwnProperty有什么优势?

[英]What Advantage Does HasOwnProperty Offer When Checking if a Property Exists As Part of An Object Literal?

The code I'm referencing comes from this answer: 我引用的代码来自以下答案:

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

What is the purpose of hasOwnProperty here? hasOwnProperty在这里的目的是什么? I've ran a version of the method that does not use it and it works just the same: 我已经运行了一个不使用该方法的版本,它的工作原理相同:

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u[this[i]] !== undefined) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

The .hasOwnProperty() test allows the code to exclude properties inherited from the prototype chain. .hasOwnProperty()测试允许代码排除从原型链继承的属性。

In your example code, if the array contained the string "toString", then your revised code would be fooled into thinking that it had already seen that value — all objects inherit the "toString" function from the Object prototype. 在您的示例代码中,如果数组包含字符串“ toString”,那么您经过修改的代码将被认为已经看到了该值-所有对象都从Object原型继承了“ toString”函数。

What if an object has a property, and that property has the value undefined or has an ancestor object with that property? 如果对象具有属性,并且该属性具有undefined的值或具有该属性的祖先对象,该怎么办?

That's the main difference. 那是主要的区别。

For example: 例如:

var a = {b:undefined};
a.b !== undefined; //false
a.hasOwnProperty("b");//true

Not having something, and having that something yourself with the value undefined are two different things. 没有东西,而自己拥有未定义值的东西是两件不同的事情。

hasOwnProperty(name) checks if the object has a property named 'name' declared directly on it. hasOwnProperty(name)检查对象是否具有直接在其上声明的名为“ name”的属性。

obj.propertyName === undefined - checks if somewhere along the prototype chain (in the object, or in its prototype, and so on) , the object has a property with name 'propertyName' and its value is undefined, or the object and its chain have no such property. obj.propertyName === undefined -检查原型链中某处(在对象中,还是在其原型中,等等),对象是否具有名称为'propertyName'的属性,并且其未定义, 或者它的链没有这样的属性。

Here are some examples illustrating the differences between the two: 以下示例说明了两者之间的区别:

var a={b:undefined};
a.hasOwnProperty(b);//true
a.b!==undefined;//false

//Create a new object, with b being the prototype
var c = Object.create(b);
c.hasOwnProperty("b");//false
c.b;//undefined;
b in c;// true
c.b!==undefined;//false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM