0

我引用的代码来自这个答案:

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

来这里的目的是hasOwnProperty什么?我运行了一个不使用它的方法版本,它的工作原理是一样的:

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

2 回答 2

4

.hasOwnProperty()测试允许代码排除从原型链继承的属性。

在您的示例代码中,如果数组包含字符串“toString”,那么您的修改后的代码会误以为它已经看到了该值——所有对象都从 Object 原型继承“toString”函数。

于 2013-05-29T18:02:53.657 回答
3

What if an object has a property, and that property has the value undefined or has an ancestor object with that property?

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.

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.

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
于 2013-05-29T18:02:52.097 回答