本文介绍一种不依赖prototype原型链和new操作符的JavaScript继承方法。通过Object.prototype扩展clone、each和extend方法,实现对象属性的浅层复制与函数重写,从而简化继承代码并提高可读性。
引言
该方案非笔者首创,系基于前人成果总结出的简洁实用JavaScript继承方法。
传统JS继承依赖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!