本文實例講述了JS自訂混合Mixin函數。分享給大家供大家參考,具體如下:
<script type="text/javascript"> /* 增加函数 */ function augment(receivingClass, givingClass) { for(methodName in givingClass.prototype) { if(!receivingClass.prototype[methodName]) { receivingClass.prototype[methodName] = givingClass.prototype[methodName]; } } } /* 改进的增加函数 */ 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]; } } } } var Author = function Author(name, books) { // 构造函数 this.name = name; this.books = books || 'default value'; }; Author.prototype = { getName: function() { return this.name; }, getBooks: function() { return this.books; } }; var Editor = function Editor() { }; Editor.prototype = { hello: function() { return 'Hello,'+this.name; } }; augment(Author, Editor); var author = new Author('Ross Harmes', ['JavaScript Design Patterns']); console.log(author.getName()); console.log(author.getBooks()); console.log(author.hello()); </script>
經過拼接處理之後,author就取得到了hello方法了,屬性還是自己的name。