手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Javascript学习笔记之 对象篇(三) : hasOwnProperty
Javascript学习笔记之 对象篇(三) : hasOwnProperty
摘要://PoisoningObject.prototypeObject.prototype.bar=1;varfoo={goo:undefine...

// 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学习笔记之 对象篇(三) : hasOwnProperty】相关文章:

JavaScript实现跑马灯抽奖活动实例代码解析与优化(二)

JavaScript的document和window对象详解

javascript动态设置样式style实例分析

javascript中clipboardData对象用法

用JavaScript实现对话框的教程

javascript基础知识分享之类与函数化

JavaScript常用函数工具集:lao-utils

prototype 1.5 & scriptaculous 1.6.1 学习笔记

Javascript获取统一管理的提示语(message)

深入理解JavaScript中的对象

精品推荐
分类导航