Mixin classes provide a way to have objects and classes share methods without being in
a parent-child relationship. It should be used where you have general-purpose methods that
you want to share among several dissimilar classes. It is possible to share all of the methods in
a mixin class, or just a few of them, using the augment function.
a parent-child relationship. It should be used where you have general-purpose methods that
you want to share among several dissimilar classes. It is possible to share all of the methods in
a mixin class, or just a few of them, using the augment function.
Mixin classes提供了一种分享类方法的方式。这种分享是没有父子继承关系的。
将基类的方法放在一个没有构造函数的类中。使用augment的方法将其复制到其他之类中。
- /* Augment function, improved. */
- function augment(receivingClass, givingClass) {
- if(arguments[2]) { // Only give certain methods. 继承个别方法
- for(var i = 2, len = arguments.length; i < len; i++) {
- receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
- }
- }
- else { // Give all methods. 继承所有
- for(methodName in givingClass.prototype) {
- if(!receivingClass.prototype[methodName]) {
- receivingClass.prototype[methodName] = givingClass.prototype[methodName];
- }
- }
- }
- }
用法是 augment(Author, Mixin, 'serialize');
传统意义上的继承如下:
- function CliBase(){};
- function CliUser(){
- CliBase.call();
- this.name;
- }