Extends 和Implements 的主要区别在于Implement 更改了类的原型,而Extend 创建了一个副本。这意味着如果您对一个类实施更改,该类的所有实例将立即继承该更改,而如果您使用 Extend,则所有现有实例将保持不变。
这是来自mootorial的报价,请查看。http://mootorial.com/wiki/mootorial/02-class/#implement-vs.-extend
至于测试——我非常建议你用忍者类构建一些示例案例并将它们放到http://www.jsfiddle.net上——然后在谷歌或 IRC 上寻求一些分析建议或 mootools 邮件列表( irc.freenode.net#mootools),所以似乎没有从 mootools 核心团队获得很多点击。理想情况下,您想与 aaron newton、arian、cpojer 或 rpflo 等人交谈 :)
更新:我什至在博客上写过这个,但我错了。Extends
mutator like和被引入的顺序只是不同Implements
。您可以实现和扩展,但您需要先声明 Extends 才能使其工作。
在这里阅读更多:http: //fragged.org/mootools-pattern-fun-class-implements-extends-at-the-same-time_1359.html
更新事实证明,在某些情况下这很有用。这是问题所在:
var ninja = new Class({
kill: function() {
alert("kill!");
}
});
var human = new Class({
initialize: function(){
alert("i r human!");
}
});
var badass = new Class({
Implements: [ninja],
Extends: human,
initialize: function() {
alert("i r badass and.. ");
this.parent();
this.kill();
}
});
new badass(); // i r badass, i r human, this.kill is not a function exception.
...根本行不通。你需要类human来实现ninja而类badass来简单地扩展human。除了人类获得一种新的杀戮方法(他们可能知道也可能不知道)的副作用之外,这将意味着坏蛋将能够使用 .kill 以及调用他的直接父母人类。
为什么不按照您想要的方式重写事物并且没有复杂性?因为您可能正在扩展像 Request.JSONP 这样的本机类,然后决定将一个新的存储类混合到您的扩展类中。真实的故事......无论哪种方式,您可能都没有重构某些可用的类的奢侈。
一个有趣的模式来克服这个问题(考虑你的 request.jsonp 的人类类,在别处定义) - 如果你只是想向你正在扩展的类添加更多的方法和属性,但不打算重用 mixin 类(忍者):
human.implement(new new Class({
kill: function() {
alert("kill!");
}
}));
var badass = new Class({
Extends: human,
initialize: function() {
alert("i r badass and.. ");
this.parent();
this.kill();
}
});
new badass(); // // i r badass, i r human, kill!
可以说,你可以这样做,human.implement({ method: function });
但一堂课可以做得更多。
如果你想保存对你的忍者类的引用以供其他用途,上面将与此相同(如果你打算重用你的 mixin):
var ninja new Class({
kill: function() {
alert("kill!");
}
});
human.implement(new ninja);
// this is what differs from say - instantiation + shared inherited properties.
// also, a constructor will work.
// the alternative would just do:
// human.prototype.kill = function() { alert("kill"); }
var badass = new Class({
Extends: human,
initialize: function() {
alert("i r badass and.. ");
this.parent();
this.kill();
}
});
new badass(); // // i r badass, i r human, kill!
希望这可以帮助某人。这是一个实际示例,我在其中扩展 Request.JSONP 并使用附加的存储类作为 mixin:http: //jsfiddle.net/dimitar/YacZe/