JavaScript 中的继承

发布于 2022-10-13 23:17:03 字数 8576 浏览 125 评论 0

众所周知,在 ES6 之前没有类的概念,所以不能像 Java 中一个 extends 关键字就搞定了继承关系,需要一些 tricks 来实现,下面就介绍一些比较常用的方法。

原型链继承

function Parent(name) { 
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
function Child(name) {
    this.name = name;
}

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

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var child = new Child('son');
child.sayName();    // child name: son

只要是原型链中出现过的原型,都可以说是该原型链派生的实例的原型。

这种方法存在两个缺点:

  1. 子类型无法给超类型传递参数,在面向对象的继承中,我们总希望通过 var child = new Child('son', 'father'); 让子类去调用父类的构造器来完成继承。而不是通过像这样 new Parent('father') 去调用父类。
  2. Child.prototype.sayName 必须写在 Child.prototype = new Parent('father'); 之后,不然就会被覆盖掉。

类式继承

function Parent(name) { 
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
Parent.prototype.doSomthing = function() {
    console.log('parent do something!');
}
function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var child = new Child('son');
child.sayName();      // child name: son
child.doSomthing();   // TypeError: child.doSomthing is not a function

相当于 Parent 这个函数在 Child 函数中执行了一遍,并且将所有与 this 绑定的变量都切换到了 Child 上,这样就克服了第一种方式带来的问题。

缺点:没有原型,每次创建一个 Child 实例对象时候都需要执行一遍 Parent 函数,无法复用一些公用函数。

组合式继承:前两种方式的结合

function Parent(name) { 
    this.name = name;
}

Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
Parent.prototype.doSomething = function() {
    console.log('parent do something!');
}
function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

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

var child = new Child('son');
child.sayName();       // child name: son
child.doSomething();   // parent do something!

组合式继承是比较常用的一种继承方法,其背后的思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。

这样,既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。

组合式继承是 JS 最常用的继承模式,但组合继承使用过程中会被调用两次:一次是创建子类型的时候,另一次是在子类型构造函数的内部。

function Parent(name) { 
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
Parent.prototype.doSomething = function() {
    console.log('parent do something!');
}
function Child(name, parentName) {
    Parent.call(this, parentName);      // 第二次调用
    this.name = name;
}

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

Child.prototype = new Parent();         // 第一次调用
Child.prototype.construtor = Child;

var child = new Child('son');
child.sayName();      
child.doSomething();   

显然从上述的代码中可以看出,第一次调用构造函数显然是没有必要的,因为第一次调用构造函数时候不需要函数内部的那些实例属性,这么写只是想获得其原型上的方法罢了,所以这时候你可能会这样写:

Child.prototype = Parent.prototype;

这样写显然是不对的:

  1. 首先,你这样写的话相当于是子类和父类都指向同一个对象,这时候如果你添加了新的方法给 Child 但实际上 Parent 并不需要,相当于强行给 Parent 添加了一个未知的方法。
  2. 其次,仔细想想,这样体现不出继承的多态性,比如此时子类想要重写父类的 getName 的方法,那么父类的方法也就会随之修改,这显然违背了多态性。

也就是说我们第一次调用构造函数的时候,其实是不管构造函数里面的内容,所以我们何不 new 一个空函数,将其 prototype 指向 Parent.prototype,代码如下:

寄生组合式继承

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}

function Child(name, parentName) {
    Parent.call(this, parentName);  
    this.name = name;    
}

function create(proto) {
    function F(){}
    F.prototype = proto;
    F.prototype.construtor = F;
    return new F();
}

Child.prototype = create(Parent.prototype);
Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}
Child.prototype.construtor = Child;

var parent = new Parent('father');
parent.sayName();    // parent name: father


var child = new Child('son', 'father');
child.sayName();     // child name: son

这就是所谓的寄生组合式继承方式,跟组合式继承的区别在于,他不需要在一次实例中调用两次父类的构造函数,假如说父类的构造器代码很多,还需要调用两次的话对系统肯定会有影响,寄生组合式继承的思想在于:用一个 F 空的构造函数去取代执行了 Parent 这个构造函数。

在上面的代码中,我们手动创建了一个 create 函数,但是其实是存在于 Object 对象中,不需要我们手动去创建,所以上面的代码可以改为:

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}

function Child(name, parentName) {
    Parent.call(this, parentName);  
    this.name = name;    
}

function inheritPrototype(Parent, Child) {
    Child.prototype = Object.create(Parent.prototype);   //修改
    Child.prototype.construtor = Child;
}

inheritPrototype(Parent, Child);

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var parent = new Parent('father');
parent.sayName();      // parent name: father

var child = new Child('son', 'father');
child.sayName();       // child name: son

ES6 继承

当然,如果你学习过 ES6,那么写继承关系就会特别简单,如果你学过 Java 就会发现,ES6 中的继承跟 Java 太像了,上述的代码可改为:

class Parent {
    constructor(name) {
	this.name = name;
    }
    doSomething() {
	console.log('parent do something!');
    }
    sayName() {
	console.log('parent name:', this.name);
    }
}

class Child extends Parent {
    constructor(name, parentName) {
	super(parentName);
	this.name = name;
    }
    sayName() {
 	console.log('child name:', this.name);
    }
}

const child = new Child('son', 'father');
child.sayName();            // child name: son
child.doSomething();        // parent do something!

const parent = new Parent('father');
parent.sayName();           // parent name: father

JavaScript(ES5)中没有像 Java 那样类的概念,写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,很容易让新学习这门语言的程序员感到困惑。但是我们可以通过原型链 prototype 来模拟类,去实现继承的相关功能。下面来看看 ES5中 实现继承常见的三种方法。代码如下:

/**
 * JavaScript(ES5)中实现继承的几种方法
 */

// 定义基类Person
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// 共享数据
Person.prototype.LEGS_NUM = 2;

// 共享方法
Person.prototype.info = function () {
  console.log('My name is ' + this.name + ' .I\'m ' + this.age + ' years old now');
};

Person.prototype.walk = function () {
  console.log(this.name + ' is walking...');
};

// Student子类
function Student(name, age, className) {
  // 调用父类
  Person.call(this, name, age);
  this.className = className;
}

// 1⃣️ 方法一:Person.prototype直接赋值给Student.prototype
// Student.prototype = Person.prototype;

// 2⃣️ 方法二:Student.prototype为Person的实例
// Student.prototype = new Person();

// 3⃣️ 方法三:创建一个空对象,对象的原型指向Person.prototype,赋值给Student.prototype
Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

// 覆盖父类的info方法
Student.prototype.info = function () {
  console.log('My name is ' + this.name + ',I\'m ' + this.age + ' years old now, and from class ' + this.className + '.');
};

// Student类的共享方法
Student.prototype.learn = function (subject) {
  console.log(this.name + ' is learning ' + subject + '.');
};

// 测试,创建一个Student的实例
var microzz = new Student('Microzz', 22, 5);
microzz.info(); // My name is Microzz,I'm 22 years old now, and from class 5.
console.log(microzz.LEGS_NUM); // 2
microzz.walk(); // Microzz is walking...
microzz.learn('JavaScript'); // Microzz is learning JavaScript.
console.log(microzz.__proto__.__proto__ === Person.prototype); // true
console.log(microzz.__proto__ === Student.prototype); // true
console.log(microzz.__proto__.constructor === Student); // true

三种方法比较

上面代码中有三种方法实现继承,现在我们可以来分析一下这几种方法。

  1. 这种方法中,Person.prototype直接赋值给Student.prototype,但是有一个很严重的问题,如果子类prototype添加新的东西的话也会改写父类。所以这种方法不推荐。
  2. 第二种方法Student.prototype为Person的实例,这也是可以实现的。但是Person构造函数有参数应该传什么呢?传任何一个都是很奇怪的。所以也不推荐。
  3. 第三种方法是比较理想的,创建一个空对象,对象的原型指向Person.prototype,赋值给Student.prototype。但是Object.create也有一点小瑕疵,因为它是ES5之后才支持的,不过我们可以通过模拟实现Object.create方法。代码如下:
if (!Object.create) {
  Object.prototype.create = function (proto) {
    function F() {}
    F.prototype = proto;
    return new F;
  }
}

这样在 ES5 中就完美实现了继承

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

温折酒

暂无简介

文章
评论
26 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文