【发布时间】:2010-09-29 08:41:14
【问题描述】:
基本上每个在 JavaScript 中写成员枚举的人都强烈主张使用 hasOwnProperty 方法以避免上升原型链。
我知道这是一种防御性编程形式,以防止迭代添加到例如Object.prototype 中的成员。但是其他继承的成员呢?比如说,原型链中非常接近的成员......您实际上希望被枚举的成员。
假设我有以下内容:
var beget = function (o) { // http://javascript.crockford.com/prototypal.html
function F() {};
F.prototype = o;
return new F();
};
var john = { name: 'john', surname: 'grech' },
mary = beget(john),
p;
mary.age = 42; //augmenting 'mary'
// 'surname' in mary => true
// mary.hasOwnProperty('surname') => false
for (p in mary) {
//skipping over non-direct members, meaning that we also skip members
//inherited from 'john'
if (!mary.hasOwnProperty(p)) {
continue;
}
console.log(p);
}
在上面的示例中,只会显示age,因为age 是mary 的唯一直接成员...另外两个成员name 和surname 是原型链。
但显然,我希望在 for..in 构造中迭代所有 3 个成员;但是如果你删除了hasOwnProperty,那么如果有人向它添加了功能,你就可以从Object.Prototype 获取成员。
所以这是我的困境。
您是否将原型继承与hasOwnProperty 方法结合使用,但冒着在枚举过程中让成员过于靠前的风险?
或者您是否使用将成员直接添加到对象而不是原型的其他继承形式?
【问题讨论】:
标签: javascript inheritance prototype hasownproperty