js对象之间的继承
js的对象之间的继承抛弃了原型与构造器的概念,而转为字面量对象之间进行属性拷贝的方式进行继承。
首先我们来写一个封装好的继承函数:
![](https://img.haomeiwen.com/i2900539/7e8a748f71662877.gif)
function extend(parent){
varchild={};
for(variin parent){
child[i]=parent[i];
}
child.uber=parent;
return child;
}
![](https://img.haomeiwen.com/i2900539/93aa33542ffc5915.gif)
函数有一个形参parent,函数内部新建一个空的子对象,这个子对象就像一个白的画板,逐渐的将父对象上的内容临摹上去。for循环当中是将父对象中的属性和方法逐个复制给子对象。再将子对象的uber指向父对象,这样调用子对象的uber属性就可以调用父对象的属性和方法了,这相当与java中的super,为什么js当中不用super呢,因为super在js中是保留字,所以采用德语与“super”同义的“uber”来替代。
下面来看看这个函数的实际应用,首先创建一个父对象:
![](https://img.haomeiwen.com/i2900539/f7558aaded4653b9.gif)
varShape={
color:"blue",
name:"shape",
getName:function(){
returnthis.name;
}
}
![](https://img.haomeiwen.com/i2900539/d3ea864cf7c07022.gif)
接着我们来实现继承,并扩展和重写子对象的一些方法:
![](https://img.haomeiwen.com/i2900539/d36d1201246573b0.gif)
varcircle=extend(Shape);
circle.name="circle";
circle.getName=function(){
return"parentName:"+this.uber.getName()+" childName:"+this.name;
}
circle.getS=function(){
returnthis.radius*this.radius*3.14;
}
circle.init=function(radius){
this.radius=radius;
}
![](https://img.haomeiwen.com/i2900539/e9a9773220f84fd0.gif)
首先使用extend函数实现继承
子对象添加了新的name属性和新的getName方法,还有扩展的getS方法和init初始化方法
getName中this.uber.getName()调用父对象的getName()方法,得到父对象的name属性,this.name得到自身的name属性。
接下来执行方法:
![](https://img.haomeiwen.com/i2900539/2c860accd97373bd.gif)
circle.init(5);
console.log(circle.name+","+circle.uber.name);
console.log(circle.getName()+","+circle.uber.getName());
console.log(circle.getS());/*结果:
circle,shape
parentName:shape childName:circle,shape
78.5*/
![](https://img.haomeiwen.com/i2900539/60d4e7171c96d0c7.gif)