JS自定义混合Mixin函数示例

高洛峰
Lepaskan: 2016-12-05 10:11:48
asal
1193 orang telah melayarinya

本文实例讲述了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 || &#39;default value&#39;;
};
Author.prototype = {
 getName: function() {
  return this.name;
 },
 getBooks: function() {
  return this.books;
 }
};
var Editor = function Editor() {
};
Editor.prototype = {
 hello: function() {
  return &#39;Hello,&#39;+this.name;
 }
};
augment(Author, Editor);
var author = new Author(&#39;Ross Harmes&#39;, [&#39;JavaScript Design Patterns&#39;]);
console.log(author.getName());
console.log(author.getBooks());
console.log(author.hello());
</script>
Salin selepas log masuk

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

Label berkaitan:
js
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan