在"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);
他在谷歌群组的帖子中这样说。