JavaScript不使用prototype和new实现继承机制
此方法并非笔者原创,笔者只是在前辈的基础上,加以总结,得出一种简洁实用的JavaScript继承方法。
传统的JavaScript继承基于prototype原型链,并且需要使用大量的new操作,代码不够简洁,可读性也不是很强,貌似还容易受到原型链污染。
笔者总结的继承方式,简洁明了,虽然不是最好的方式,但希望能给读者带来启发。
好了,废话不多说,直接看代码,注释详尽,一看就懂~~~
/**
*Createdby杨元on14-11-11.
*不使用prototype实现继承
*
*/
/**
*Javascript对象复制,仅复制一层,且仅复制function属性,不通用!
*@paramobj 要复制的对象
*@returns Object
*/
Object.prototype.clone=function(){
var_s=this,
newObj={};
_s.each(function(key,value){
if(Object.prototype.toString.call(value)==="[objectFunction]"){
newObj[key]=value;
}
});
returnnewObj;
};
/**
*遍历obj所有自身属性
*
*@paramcallback回调函数。回调时会包含两个参数:key属性名,value属性值
*/
Object.prototype.each=function(callback){
varkey="",
_this=this;
for(keyin_this){
if(Object.prototype.hasOwnProperty.call(_this,key)){
callback(key,_this[key]);
}
}
};
/**
*创建子类
*@paramextobj,包含需要重写或扩展的方法。
*@returnsObject
*/
Object.prototype.extend=function(ext){
varchild=this.clone();
ext.each(function(key,value){
child[key]=value;
});
returnchild;
};
/**
*创建对象(实例)
*@paramarguments可接受任意数量参数,作为构造器参数列表
*@returnsObject
*/
Object.prototype.create=function(){
varobj=this.clone();
if(obj.construct){
obj.construct.apply(obj,arguments);
}
returnobj;
};
/**
*UseageExample
*使用此种方式继承,避免了繁琐的prototype和new。
*但是目前笔者写的这段示例,只能继承父类的function(可以理解为成员方法)。
*如果想继承更丰富的内容,请完善clone方法。
*
*
*/
/**
*动物(父类)
*@type{{construct:construct,eat:eat}}
*/
varAnimal={
construct:function(name){
this.name=name;
},
eat:function(){
console.log("Mynameis"+this.name+".Icaneat!");
}
};
/**
*鸟(子类)
*鸟类重写了父类eat方法,并扩展出fly方法
*@type{子类|void}
*/
varBird=Animal.extend({
eat:function(food){
console.log("Mynameis"+this.name+".Icaneat"+food+"!");
},
fly:function(){
console.log("Icanfly!");
}
});
/**
*创建鸟类实例
*@type{Jim}
*/
varbirdJim=Bird.create("Jim"),
birdTom=Bird.create("Tom");
birdJim.eat("worm"); //MynameisJim.Icaneatworm!
birdJim.fly(); //Icanfly!
birdTom.eat("rice"); //MynameisTom.Icaneatrice!
birdTom.fly(); //Icanfly!