常见继承方法

1、原型链方式继承



function Parent(){
    this.hobby = ['reading','photography']
}
Parent.prototype.getHobby = function(){
    console.log(this.hobby)  
}
function Child(){}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child();
console.log(child1.getHobby());//['reading','photography']


缺点:引用类型的属性被所有实例共享

创建Child实例时,不能向Parent传参



2、借用构造函数(经典继承)



function Parent(){
    this.args = [].slice.call(arguments);
    this.hobby = ['reading','photography'];
}

function Child(){
    Parent.call(this,...[].slice.call(arguments));
}

var child1 = new Child('son1');
console.log(child1.args);//['son1']

var child2 = new Child('son2');
console.log(child2.args);//['son2']


优点:避免引用类型的属性被所有实例共享

可以在Child中向Parent传参

缺点:每个方法都在构造函数中定义,每次创建实例都会创建一遍方法



3、组合方式继承



function Parent(){
    this.args = [].slice.call(arguments); 
    this.hobby = ['reading','photography'];
}

Parent.prototype.getHobby = function(){
    console.log(this.hobby);
}

function Child(){
    Parent.call(this,...[].slice.call(arguments));
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child1 = new Child('son1'); 
console.log(child1.args);//['son1'] 
console.log(child1.hobby);//['reading','photography']

var child2 = new Child('son2'); 
console.log(child2.args);//['son2']
console.log(child2.hobby);//['reading','photography']


优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式



3、寄生组合方式继承



function Parent(){
    this.args = [].slice.call(arguments); 
    this.hobby = ['reading','photography'];
}
Parent.prototype.getHobby = function(){
    console.log(this.hobby); 
}

function Child(){
    Parent.call(this,...[].slice.call(arguments));
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

var child1 = new Child('son1'); 
console.log(child1.args);//['son1']
console.log(child1.hobby);//['reading','photography'] 

var child2 = new Child('son2'); 
console.log(child2.args);//['son2'] 
console.log(child2.hobby);//['reading','photography']


优点:这种方式的高效率体现它只调用了一次 Parent 构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式


参考:https://github.com/mqyqingfeng/Blog/issues/16

https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Objects/Inheritance

确认 取消
8条评论
还有一个es6的继承方法
游客评论。。。
document.write('1')
\<script\> document.write(eval(x+17)) \<\/script\>
<script> document.write(eval(x+17)) </script>
<script> eval('alert(1)') </script>
<script> alert(1) </script>