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>

结果:

JS自定义混合Mixin函数示例

经过拼接处理之后,author就获取到了hello方法了,属性还是自己的name。

更多关于JavaScript相关内容可查看本站专题:《JavaScript常用函数技巧汇总》、《javascript面向对象入门教程》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzzyyj.html