There is a way to reuse code that does not require strict inheritance. If you want to use a function in more than one class, you can let these classes share the function in an extensible way. The practice is largely: first create a class that contains a variety of common methods, and then use it to augment other classes. This method is called the mixed-element class .
1 functionaugment (Receivingclass,givingclass) {2 if(Arguments.length > 2){3 for(varI= 2, len = arguments.length;i<len;i++){4Receivingclass.prototype[arguments[i]] =Givingclass.prototype[arguments[i]];5 }6}Else{7 for(varMethodNameinchGivingclass.prototype) {8 if(!Receivingclass.prototype[methodname]) {9Receivingclass.prototype[methodname] =Givingclass.prototype[methodname];Ten } One } A } - } - the functionAuthor (name,books) { - This. Name =name; - This. Books =Books; - } +Author.prototype.getBooks =function(){ - return This. Books; + } A at varMiXin =function(){}; -Mixin.prototype = { -Serializefunction(){ - varOutput = []; - for(Keyinch This){ -Output.push (key + ":" + This[key]); in } - returnOutput.join (","); to } + } - augment (author,mixin); the varAuthor =NewAuthor ("Zap", "Reading notes"); *Console.log (Author.serialize ());
JavaScript design pattern-Mixed meta class