用Javascript编写一个扩展方法

Writing an Extend Method in Javascript

本文关键字:一个 扩展 方法 Javascript      更新时间:2023-09-26

我想知道是否有人可以帮助我理解为什么有必要添加以下行…

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继承了其原型的infoForAllThingsspeak属性,当创建t1时,它被设置为Thing.prototype。但是extend函数使用hasOwnProperty将它们过滤掉,因此不会将它们复制到它创建的副本中,因此它们不存在于t2上。t2name因为它被直接赋值为对象,它不是来自原型,但其他的来自原型,所以不会被复制。