您好,欢迎访问一九零五行业门户网

Javascript学习笔记之 对象篇(三) : hasOwnProperty_基础知识

// poisoning object.prototypeobject.prototype.bar = 1;var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasownproperty('bar'); // falsefoo.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 purposeobject.prototype.hasownproperty.call(foo, 'bar'); // true
总结
当判断对象属性存在时,hasownproperty 是唯一可以依赖的方法。这里还要提醒下,当我们使用 for in loop 来遍历对象时,使用 hasownproperty 将会很好地避免来自原型对象扩展所带来的困扰。
其它类似信息

推荐信息