我想知道是否有人可以帮助我理解为什么有必要添加以下行...
if (!obj.hasOwnProperty(key)) continue;
...在以下方法中:
extend: function(obj) {
// shallow copy
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
this[key] = obj[key];
}
}
我想知道是否有人可以帮助我理解为什么有必要添加以下行...
if (!obj.hasOwnProperty(key)) continue;
...在以下方法中:
extend: function(obj) {
// shallow copy
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
this[key] = obj[key];
}
}
当您使用for-in
循环遍历对象的属性名称时,您会看到所有可枚举的属性,包括对象从其原型继承的那些属性。似乎实现该方法的人不想复制从原型继承的属性,因此只包含对象本身直接拥有的属性。
这是一个例子:
function Thing(name) {
this.name = name;
}
Thing.prototype.speak = function() {
console.log("I'm " + this.name);
};
Thing.prototype.infoForAllThings = 42;
var t1 = new Thing("Fred");
console.log(t1.name); // "Fred"
console.log(t1.infoForAllThings); // "42"
t1.speak(); // "I'm Fred"
var t2 = extend(t1); // (Where `extend` is like your function,
// but returns the object rather than using `this`
console.log(t2.name); // "Fred"
console.log(t2.infoForAllThings); // "undefined"
t2.speak(); // Error
在上面,从它的原型t1
继承infoForAllThings
和speak
属性,它被设置为Thing.prototype
创建时间t1
。但是该extend
函数用于hasOwnProperty
将它们过滤掉,因此不会将它们复制到它创建的副本中,因此它们不存在于t2
. 因为那是直接分配t2
给对象的,它不是来自原型,但其他来自原型,所以不会被复制。name