这个mixins代码是书中的错误吗;面向对象JavaScript的原理”;

is this mixins code an error of book "The Principles of Object-Oriented JavaScript"

本文关键字:面向对象 JavaScript 错误 代码 mixins 这个      更新时间:2023-09-26

在"mixins"一章中,有一个示例代码

function mixin(receiver, supplier) {
    for (var property in supplier) {
        if (supplier.hasOwnProperty(property)) {
            receiver[property] = supplier[property]
        }
    }
    return receiver;
}
function EventTarget(){
}
EventTarget.prototype = {
  add: function(){console.log("add");}
};
function Person(name) {
      this.name = name;
  }
mixin(Person.prototype, new EventTarget());
mixin(Person.prototype, {
      constructor: Person,
      sayName: function() {
          console.log(this.name);
          this.fire({ type: "namesaid", name: name });
      }
  });
  var person = new Person("Nicholas");

据我所知,这是试图将属性从EventTarget.prototype复制到Person.prototype中

mixin(Person.prototype, new EventTarget());

应该是

mixin(Person.prototype, EventTarget.prototype);

这段代码我说得对吗?

是的,这(可能)是一个错误。

(自定义)EventTarget构造函数定义为

function EventTarget(){
  // No property assigned to `this`
}
EventTarget.prototype = {
  add: function(){console.log("add");}
};

因此,EventTarget实例将从EventTarget.prototype继承add方法,但不会有任何自己的属性。

然而,函数mixin只分配自己的属性:

function mixin(receiver, supplier) {
  for (var property in supplier)
    if (supplier.hasOwnProperty(property)) // <--
      receiver[property] = supplier[property]
  return receiver;
}

因此,以下代码对没有任何作用

mixin(Person.prototype, new EventTarget());

根据作者Nicholas Zakas的说法,是的,这确实是一个错误,应该是:

mixin(Person.prototype, EventTarget.prototype);

他在谷歌群组的帖子中这样说。