发布于 2016-08-21 06:43:41 | 103 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Javascript教程,程序狗速度看过来!

JavaScript客户端脚本语言

Javascript 是一种由Netscape的LiveScript发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如Perl,遗留的速度问题,为客户提供更流畅的浏览效果。


判断一个属性是定义在对象本身而不是继承自原型链,我们需要使用从 Object.prototype 继承而来的 hasOwnProperty 方法。 hasOwnProperty 方法是 Javascript 中唯一一个处理对象属性而不会往上遍历原型链的。

// 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 将会很好地避免来自原型对象扩展所带来的困扰。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务