javascrpt 继承

一、基于原型链方式实现的继承

缺点:无法从子类中调用父类的构造函数,所以没有办法把子类的属性赋值到父类中。

如果父类中有引用类型,例如:数组。此时这个引用类型会添加到子类的原型当中,一但子类某个对象修改,则影响全部其他对象。

参考代码:

  

function Parent(){
    this.pv = "parent";
    this.color = ["red","yellow"];
}
Parent.prototype.showParentValue = function(){
    alert(this.pv);
}
function Child(){
    this.cv = "child";
}
Child.prototype = new Parent();
Child.prototype.showChildValue = function(){
    alert(this.cv);
}

var c1  = new Child();
//Child中的原型的color被修改
c1.color.push("bule");//red yellow blue
alert(c1.color);
var c2 = new Child();//同样影响c2中color值
alert(c2.color);//red yellow blue

二、基于伪装方式实现的继承

缺点:没有完成原型的指向。只能继承父类属性无法完成父类方法的继承。

参考代码:

function Parent(name){
    this.color = ["red","blue"];
    this.name=name;
}
function Child(name,age){
    this.age = age;
    Parent.call(this,name);//用第一个变量的上下文调用这个函数
}
var c1 = new Child("Leon",12);
var c2 = new Child("Ada",22);
alert(c1.name + "," +c1.age);
alert(c2.name + "," +c2.age);

三、终极方案-组合方式实现继承
原理:通过原型链方式实现方法的继承,通过伪装方式实现属性的继承。

参考代码:

/**
 * 组合的实现方式是属性通过伪造的方法实现,方法通过原型链的方式实现
 */
function Parent(name){
    this.color = ["red","blue"];
    this.name = name;
}
Parent.prototype.ps = function(){
    alert(this.name + "[" + this.color + "]");
}
function Child(name,age){
    //已经完成了伪造
    Parent.call(this,name);
    this.age = age;
}
Child.prototype = new Parent();
Child.prototype.say = function(){
    alert(this.name + "," + this.age + "[" + this.color + "]")
}

var c1 = new Child("rigid",30);
    
原文地址:https://www.cnblogs.com/rigid/p/4300714.html