Javascript学习笔记之 对象篇(三) : hasOwnProperty

// Poisoning Object.prototype

Object.prototype.bar = 1;

var foo = {goo: undefined};

foo.bar; // 1

'bar' in foo; // true

foo.hasOwnProperty('bar'); // false

foo.hasOwnProperty('goo'); // true

在这里,只有 hasOwnProperty 能给出正确答案,这在遍历一个对象的属性时是非常必要的。Javascript 中没有其他方法能判断一个属性是定义在对象本身还是继承自原型链。

hasOwnProperty 作为属性

Javascript 并未将 hasOwnProperty 设为敏感词,这意味着你可以拥有一个命名为 hasOwnProperty 的属性。这个时候你无法再使用本身的 hasOwnProperty 方法来判断属性,所以你需要使用外部的 hasOwnProperty 方法来进行判断。

var foo = {

hasOwnProperty: function() {

return false;

},

bar: 'Here be dragons'

};

foo.hasOwnProperty('bar'); // always returns false

// Use another Object's hasOwnProperty and call it with 'this' set to foo

({}).hasOwnProperty.call(foo, 'bar'); // true

// It's also possible to use hasOwnProperty from the Object

// prototype for this purpose

Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

总结

当判断对象属性存在时,hasOwnProperty 是唯一可以依赖的方法。这里还要提醒下,当我们使用 for in loop 来遍历对象时,使用 hasOwnProperty 将会很好地避免来自原型对象扩展所带来的困扰。

下面是其他网友的补充:

Javascript中Object对象原型上的hasOwnProperty()用来判断一个属性是定义在对象本身而不是继承自原型链。

obj.hasOwnProperty(prop)

参数 prop

要检测的属性 字符串 名称或者 Symbol(ES6)

o = new Object();

o.prop = 'exists';

o.hasOwnProperty('prop'); // 返回 true

o.hasOwnProperty('toString'); // 返回 false

o.hasOwnProperty('hasOwnProperty'); // 返回 false

使用hasOwnProperty作为某个对象的属性名

因为javascript没有将hasOwnProperty作为一个敏感词,所以我们很有可能将对象的一个属性命名为hasOwnProperty,这样一来就无法再使用对象原型的 hasOwnProperty 方法来判断属性是否是来自原型链。

var foo = {

hasOwnProperty: function() {

return false;

},

bar: 'Here be dragons'

};

foo.hasOwnProperty('bar'); // 始终返回 false

不能使用 该对象.hasOwnProperty 这种方法,怎么来解决这个问题呢?我们需要使用原型链上真正的 hasOwnProperty 方法:

({}).hasOwnProperty.call(foo, 'bar'); // true

// 或者:

Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

以上是 Javascript学习笔记之 对象篇(三) : hasOwnProperty 的全部内容, 来源链接: utcz.com/z/321233.html

回到顶部