<
>

深入讲解JavaScript之继承的多种方式和优缺点

2022-04-14 21:33:20 来源:易采站长站 作者:

目录
1.原型链继承2.借用构造函数(经典继承)3.组合继承4.原型式继承5. 寄生式继承6. 寄生组合式继承

1.原型链继承

function Parent () {    this.name = 'kevin';}Parent.prototype.getName = function () {    console.log(this.name);}function Child () {}Child.prototype = new Parent();var child1 = new Child();console.log(child1.getName()) // kevin

问题:

1.引用类型的属性被所有实例共享,举个例子:

function Parent () {    this.names = ['kevin', 'daisy'];}function Child () {}Child.prototype = new Parent();var child1 = new Child();child1.names.push('yayu');console.log(child1.names); // ["kevin", "daisy", "yayu"]var child2 = new Child();console.log(child2.names); // ["kevin", "daisy", "yayu"]

2.在创建 Child 的实例时,不能向Parent传参

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

function Parent () {    this.names = ['kevin', 'daisy'];}function Child () {    Parent.call(this);}var child1 = new Child();child1.names.push('yayu');console.log(child1.names); // ["kevin", "daisy", "yayu"]var child2 = new Child();console.log(child2.names); // ["kevin", hthWGiMWBE"daisy"]

优点:

1.避免了引用类型的属性被所有实例共享 2.可以在 Child 中向 Parent 传参

举个例子:

function Parent (name) {    this.name = name;}function Child (name) {    Parent.call(this, name);}var child1 = new Child('kevin');console.log(child1.name); // kevinvar child2 = new Child('daisy');console.log(child2.name); // daisy

缺点:

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

3.组合继承

原型链继承和经典继承双剑合璧。

function Parent (name) {    this.name = name;    this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () {    console.log(this.name)}function Child (name, age) {    Parent.call(this, name);    this.age = age;}Child.prototype = new Parent();var child1 = new Child('kevin', '18');child1.colors.push('black');console.log(child1.name); // kevinconsole.log(child1.age); // 18console.log(child1.colors); // ["red", "blue", "green", "black"]var child2 = new Child('daisy', '20');console.log(child2.name); // daisyconsole.log(child2.age); // 20console.log(child2.colors); // ["red", "blue", "green"]

优点:融合原型链继承和构》中对寄生组合式继承的夸赞就是:

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

暂时禁止评论

微信扫一扫

易采站长站微信账号