首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:17:17
字体:
来源:转载
供稿:网友

写在前面

本文讲解JavaScript各种继承方式和优缺点。

注意:

跟《JavaScript深入之创建对象》一样,更像是笔记。

哎,再让我感叹一句:《JavaScript高级程序设计》写得真是太好了!

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", "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"]

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

4.原型式继承

function createObj(o) {  function F(){}  F.prototype = o;  return new F();}

就是 ES5 Object.create 的模拟实现,将传入的对象作为创建的对象的原型。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选