JS类的实现
2015-09-17 17:39
609 查看
1个月前写过最简单的那种,再重新实现一遍
//类的实现,一个参数创建类,两个参数继承类 var Klass = function (parent, options) { var hasOwn = Object.prototype.hasOwnProperty, isFunc = function(obj) { return typeof obj === 'function'; }, //中间函数避免执行父类构造函数 Func = function () { },//返回的子类 Child = function () { isFunc(this.initialize) && this.initialize.apply(this, arguments); }, k; //参数check if (arguments.length === 0 || arguments.length > 2) throw new Error("只接受1个或2个参数"); //只传入一个参数对象 if (!isFunc(parent)) { options = parent; parent = null; } //继承父类 if (parent) { Func.prototype = parent.prototype; Child.prototype = new Func(); Child.superproto = parent.prototype; Child.prototype.constructor = Child; } //添加options for (k in options) { if(hasOwn.call(options, k)) Child.prototype[k] = options[k]; } return Child; }; //测试 var Person = Klass({ initialize: function(opt) { this.name = 'unnamed'; $.extend(this, opt); }, getName: function () { return this.name; }, say: function() { console.log("hello world"); } }), Player = Klass(Person, { play: function () { console.log("i'm playing " + this.game); } }), player1 = new Player({ name: 'bobo', game: 'Dota2' }); player1.play(); // "i'm playing Dota2" player1.say(); // "hello world" console.log(player1.getName()); // "bobo"
相关文章推荐
- javascript 和 jq 的调试 用console.log() 函数
- js javascript 获取url,获得当前页面的url,静态html文件js读取url参数
- 用js控制frame框架自适应高度
- createjs-打豆豆小游戏制作(4)
- js之History对象
- js动态引入的四种方式
- Javascript学习笔记【第三章】2
- JS类的封装及实现代码
- javascript控制开始日期,和结束日期在同一个月
- Jsp九大内置对象及四个作用域
- (转)js prototype 详解
- JavaScript编码风格指南(中文版)
- javascript必知必会之prototype
- JSON返回值不是预定的值,而是无效时的值(情况不定)
- js根据URL获取参数的值
- javaScript中的页面传值
- JSP四大作用域
- 搭建D3.js的开发环境
- 原生JS+tween.js模仿微博发布效果
- Javascript事件对象