js对象之间的继承

2019-04-08  本文已影响0人  凡凡的小web

js的对象之间的继承抛弃了原型与构造器的概念,而转为字面量对象之间进行属性拷贝的方式进行继承。 

首先我们来写一个封装好的继承函数:

function extend(parent){

    varchild={};

    for(variin parent){

        child[i]=parent[i];

    }

    child.uber=parent;

    return child;

}

 函数有一个形参parent,函数内部新建一个空的子对象,这个子对象就像一个白的画板,逐渐的将父对象上的内容临摹上去。for循环当中是将父对象中的属性和方法逐个复制给子对象。再将子对象的uber指向父对象,这样调用子对象的uber属性就可以调用父对象的属性和方法了,这相当与java中的super,为什么js当中不用super呢,因为super在js中是保留字,所以采用德语与“super”同义的“uber”来替代。

下面来看看这个函数的实际应用,首先创建一个父对象:

varShape={

    color:"blue",

    name:"shape",

    getName:function(){

        returnthis.name;

    }

}

接着我们来实现继承,并扩展和重写子对象的一些方法:

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;

}

首先使用extend函数实现继承

子对象添加了新的name属性和新的getName方法,还有扩展的getS方法和init初始化方法

getName中this.uber.getName()调用父对象的getName()方法,得到父对象的name属性,this.name得到自身的name属性。

接下来执行方法:

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://www.cnblogs.com/smartXiang/p/5890952.html

上一篇 下一篇

猜你喜欢

热点阅读