JS自定义混合Mixin函数示例

作者:牛逼的霍啸林 时间:2024-04-16 10:29:41 

本文实例讲述了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程序设计有所帮助。

标签:JS,函数
0
投稿

猜你喜欢

  • Golang算法之田忌赛马问题实现方法分析

    2023-06-29 06:07:24
  • asp实现新评论自动发短信提示的代码

    2011-03-07 10:38:00
  • python判断数字是否是超级素数幂

    2023-12-24 06:16:31
  • python写入xml文件的方法

    2023-01-01 15:08:54
  • python networkx 包绘制复杂网络关系图的实现

    2021-03-27 06:11:39
  • python3.7添加dlib模块的方法

    2023-09-16 03:58:55
  • Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)

    2023-08-26 16:08:33
  • 利用SQL语句对不同数据库进行高效果分页

    2008-11-28 14:44:00
  • pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换

    2023-08-12 07:44:34
  • oracle学习笔记(三)

    2012-01-05 19:28:42
  • 从网页设计开始

    2008-06-30 12:17:00
  • win10 64位 MySQL8.0下载和安装教程图解

    2024-01-13 06:34:29
  • Git的基础文件操作初始化查看添加提交示例教程

    2023-12-25 19:43:21
  • 浅谈MySQL之浅入深出页原理

    2024-01-18 20:38:29
  • 再谈“字符串拼接”的效率

    2009-04-30 12:48:00
  • Centos8(最小化安装)全新安装Python3.8+pip的方法教程

    2022-11-09 06:00:27
  • 利用Python第三方库xlrd读取Excel中数据实例代码

    2023-02-17 05:28:58
  • 100 个 Python 小例子(练习题一)

    2022-09-25 20:45:52
  • golang gorm框架数据库的连接操作示例

    2024-01-21 06:52:56
  • python实现五子棋游戏(pygame版)

    2021-09-15 16:01:42
  • asp之家 网络编程 m.aspxhome.com