js 继承的三种方式构造函数、原型链、组合继承

第一种方式:js使用构造函数的继承。

缺点:无法继承父类的原型链。

// 构造函数继承 缺点:没有继承原型链

function Parent1(){

  this.name = 'Parent'

}

Parent1.prototype.sayParent = function(){

  console.log('say Parent!')

}

function Child(){

  Parent1.call(this)

  this.type = 'child'

}

var child = new Child()

console.log(child) // 下面运行结果 

child.sayParent() // 不能继承父类原型的方法

构造函数的继承运行结果


第二种:使用原型链继承的方式

// 缺点:父类的属性为引用类型时候,子类实例众多使用,有一个修改,其它也会变成修改值

function Parent2() {

  this.name = "Parent";

  this.ary = [1,2,3]

}

Parent2.prototype.sayParent = function() {

  console.log("say Parent!");

};

function Child() {

  this.type = "child";

}

Child.prototype = new Parent2();

var child1 = new Child();

var child2 = new Child();

console.log(child1.ary);

console.log(child2.ary);

child1.ary.push(5)

console.log(child1.ary); 

console.log(child2.ary) // 这里也造成了ary 数组也增加了

child1.sayParent();


原型链继承的方式


第三种 // 使用组合继承的方式。

解决了上面两种缺点。

function Parent3() {

  this.name = "Parent";

  this.ary = [1,2,3]

}

Parent3.prototype.sayParent = function() {

  console.log("say Parent!");

};

function Child() {

  Parent3.call(this);

  this.type = "child";

}

Child.prototype = Object.create(Parent3.prototype);

Child.prototype.constructor = Child;

var child1 = new Child();

var child2 = new Child();

console.log(child1.ary);

console.log(child2.ary);

child1.ary.push(5)

console.log(child1.ary);

console.log(child2.ary)

child1.sayParent();

console.log(child1.constructor);

组合继承的方式
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容