这篇文章主要介绍了 JavaScript 不使用 prototype 和 new 实现继承机制的相关资料, 需要的朋友可以参考下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
此方法并非笔者原创,笔者只是在前辈的基础上,加以总结,得出一种简洁实用的 JavaScript 继承方法。
传统的 JavaScript 继承基于 prototype 原型链,并且需要使用大量的 new 操作,代码不够简洁,可读性也不是很强,貌似还容易受到原型链污染。
笔者总结的继承方式,简洁明了,虽然不是最好的方式,但希望能给读者带来启发。
好了,废话不多说,直接看代码,注释详尽,一看就懂~~~
- /**
- * Created by 杨元 on 14-11-11.
- * 不使用prototype实现继承
- *
- */
- /**
- * Javascript对象复制,仅复制一层,且仅复制function属性,不通用!
- * @param obj 要复制的对象
- * @returns Object
- */
- Object.prototype.clone = function(){
- var _s = this,
- newObj = {};
- _s.each(function(key, value){
- if(Object.prototype.toString.call(value) === "[object Function]"){
- newObj[key] = value;
- }
- });
- return newObj;
- };
- /**
- * 遍历obj所有自身属性
- *
- * @param callback 回调函数。回调时会包含两个参数: key 属性名,value 属性值
- */
- Object.prototype.each = function(callback){
- var key = "",
- _this = this;
- for (key in _this){
- if(Object.prototype.hasOwnProperty.call(_this, key)){
- callback(key, _this[key]);
- }
- }
- };
- /**
- * 创建子类
- * @param ext obj,包含需要重写或扩展的方法。
- * @returns Object
- */
- Object.prototype.extend = function(ext){
- var child = this.clone();
- ext.each(function(key, value){
- child[key] = value;
- });
- return child;
- };
- /**
- * 创建对象(实例)
- * @param arguments 可接受任意数量参数,作为构造器参数列表
- * @returns Object
- */
- Object.prototype.create = function(){
- var obj = this.clone();
- if(obj.construct){
- obj.construct.apply(obj, arguments);
- }
- return obj;
- };
- /**
- * Useage Example
- * 使用此种方式继承,避免了繁琐的prototype和new。
- * 但是目前笔者写的这段示例,只能继承父类的function(可以理解为成员方法)。
- * 如果想继承更丰富的内容,请完善clone方法。
- *
- *
- */
- /**
- * 动物(父类)
- * @type {{construct: construct, eat: eat}}
- */
- var Animal = {
- construct: function(name){
- this.name = name;
- },
- eat: function(){
- console.log("My name is "+this.name+". I can eat!");
- }
- };
- /**
- * 鸟(子类)
- * 鸟类重写了父类eat方法,并扩展出fly方法
- * @type {子类|void}
- */
- var Bird = Animal.extend({
- eat: function(food){
- console.log("My name is "+this.name+". I can eat "+food+"!");
- },
- fly: function(){
- console.log("I can fly!");
- }
- });
- /**
- * 创建鸟类实例
- * @type {Jim}
- */
- var birdJim = Bird.create("Jim"),
- birdTom = Bird.create("Tom");
- birdJim.eat("worm"); //My name is Jim. I can eat worm!
- birdJim.fly(); //I can fly!
- birdTom.eat("rice"); //My name is Tom. I can eat rice!
- birdTom.fly(); //I can fly!
来源: