1、原型继承

在上一篇中,我们提到,JS中原型继承的本质,实际上就是 “将构造函数的原型对象,指向由另一个构造函数创建的实例”。


这里,我们就原型继承的概念,再进行详细的理解。首先回顾一下之前的一个示例,Student构造函数 和 原型链:
function Student(props) {
this.name = props.name || 'Unnamed';
} Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
7
 
1
function Student(props) { 
2
    this.name = props.name || 'Unnamed';
3
}
4

5
Student.prototype.hello = function () {
6
    alert('Hello, ' + this.name + '!');
7
}


现在我们希望能由Student扩展出一个如 PrimaryStudent,要求这个新构造函数创建的对象能够调用自己原型对象的方法之外,还可以调用Student.prototype原型对象的方法,相当于实现继承:
function PrimaryStudent(props) {
// 调用Student构造函数,绑定this变量
Student.call(this, props);
this.grade = props.grade || 1;
}
5
 
1
function PrimaryStudent(props) {
2
    // 调用Student构造函数,绑定this变量
3
    Student.call(this, props);
4
    this.grade = props.grade || 1;
5
}

然而我们的原型链目前是这样:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Object.prototype ----> null
1
 
1
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Object.prototype ----> null

为了达到这个目的,我们的原型链必须变成这样:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
1
 
1
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null

你说,使用 PrimaryStudent.prototype = Student.prototype; 不就可以了?如果这样做,我们看看原型链变成了什么样:
new PrimaryStudent() ----> Student.prototype ----> Object.prototype ----> null
1
 
1
new PrimaryStudent() ----> Student.prototype ----> Object.prototype ----> null

之前我们形象地比喻过说,原型对象就像是对象的老爹,构造函数是老妈。这里只是换了个老爹而已,而我们希望的是,老爹的老爹(就是它的爷爷)是Student.prototype,所以,这样粗暴地直接定义是不行的。另外,在新构造函数中调用了Student的构造函数,也不等于继承,毕竟原型链摆在那,没变。

事实上,我们通过另一个对象来链接 PrimaryStudent 和 Student 就可以了:
var bridge = {};  //创建一个没有内容的对象
bridge.__proto__ = Student.prototype; //让这个对象的原型对象是Student.prototype
bridge.constructor = PrimaryStudent; //让这个对象的构造函数为PrimaryStudent
PrimaryStudent.prototype = bridge; //让PrimaryStudent的原型对象指向bridge 这样一来,原型链就变成了:
new PrimaryStudent() ----> PrimaryStudent.prototype(bridge) ----> Student.prototype ----> Object.prototype ----> null 按照我们比喻的说法,就是:
- 让Student有个儿子bridge(bridge.__proto__ = Student.prototype;)
- 然后这个娃和PrimaryStudent结婚了(bridge.constructor = PrimaryStudent; PrimaryStudent.prototype = bridge;)
- 那么自然PrimaryStudent的子女(通过PrimaryStudent创建的对象),既会老爹bridge的技能,也会爷爷Student的技能” //验证一下
bridge.do = function(){alert("hahaha")};
var xiaoming = new PrimaryStudent({name:'xiaoming', grade:2});
xiaoming.do(); // 弹框alert("hahaha"); //验证原型
xiaoming.__proto__ === PrimaryStudent.prototype; //true
xiaoming.__proto__.__proto__ === Student.prototype; //true //验证继承关系
xiaoming instanceof PrimaryStudent; //true
xiaoming instanceof Student; //true
25
 
1
var bridge = {};  //创建一个没有内容的对象
2
bridge.__proto__ = Student.prototype;  //让这个对象的原型对象是Student.prototype
3
bridge.constructor = PrimaryStudent;  //让这个对象的构造函数为PrimaryStudent
4
PrimaryStudent.prototype = bridge;  //让PrimaryStudent的原型对象指向bridge
5

6
这样一来,原型链就变成了:
7
new PrimaryStudent() ----> PrimaryStudent.prototype(bridge) ----> Student.prototype ----> Object.prototype ----> null
8

9
按照我们比喻的说法,就是:
10
- 让Student有个儿子bridge(bridge.__proto__ = Student.prototype;)
11
- 然后这个娃和PrimaryStudent结婚了(bridge.constructor = PrimaryStudent; PrimaryStudent.prototype = bridge;)
12
- 那么自然PrimaryStudent的子女(通过PrimaryStudent创建的对象),既会老爹bridge的技能,也会爷爷Student的技能”
13

14
//验证一下
15
bridge.do = function(){alert("hahaha")};
16
var xiaoming = new PrimaryStudent({name:'xiaoming', grade:2});
17
xiaoming.do(); // 弹框alert("hahaha");
18

19
//验证原型
20
xiaoming.__proto__ === PrimaryStudent.prototype; //true
21
xiaoming.__proto__.__proto__ === Student.prototype; //true
22

23
//验证继承关系
24
xiaoming instanceof PrimaryStudent; //true
25
xiaoming instanceof Student; //true

我们也可以参考发明JSON的大神道格拉斯的做法,中间对象用空函数F来实现:
// PrimaryStudent构造函数:
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
} // 空函数F,用于后面起桥接作用
function F() {
} // 把F的原型指向Student.prototype,这样通过F创建的对象,其__proto__属性就是Student.prototype
F.prototype = Student.prototype; // 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype
PrimaryStudent.prototype = new F(); // 把PrimaryStudent原型的构造函数修复为PrimaryStudent
PrimaryStudent.prototype.constructor = PrimaryStudent; // 继续在PrimaryStudent原型(就是new F()对象)上定义方法
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
}; // 创建xiaoming
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2 // 验证原型
xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true // 验证继承关系
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true
39
 
1
// PrimaryStudent构造函数:
2
function PrimaryStudent(props) {
3
    Student.call(this, props);
4
    this.grade = props.grade || 1;
5
}
6

7
// 空函数F,用于后面起桥接作用
8
function F() {
9
}
10

11
// 把F的原型指向Student.prototype,这样通过F创建的对象,其__proto__属性就是Student.prototype
12
F.prototype = Student.prototype;
13

14
// 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype
15
PrimaryStudent.prototype = new F();
16

17
// 把PrimaryStudent原型的构造函数修复为PrimaryStudent
18
PrimaryStudent.prototype.constructor = PrimaryStudent;
19

20
// 继续在PrimaryStudent原型(就是new F()对象)上定义方法
21
PrimaryStudent.prototype.getGrade = function () {
22
    return this.grade;
23
};
24

25
// 创建xiaoming
26
var xiaoming = new PrimaryStudent({
27
    name: '小明',
28
    grade: 2
29
});
30
xiaoming.name; // '小明'
31
xiaoming.grade; // 2
32

33
// 验证原型
34
xiaoming.__proto__ === PrimaryStudent.prototype; // true
35
xiaoming.__proto__.__proto__ === Student.prototype; // true
36

37
// 验证继承关系
38
xiaoming instanceof PrimaryStudent; // true
39
xiaoming instanceof Student; // true



如果把继承的动作封装成一个函数,还可以隐藏F的定义,并简化代码:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
6
 
1
function inherits(Child, Parent) {
2
    var F = function () {};
3
    F.prototype = Parent.prototype;
4
    Child.prototype = new F();
5
    Child.prototype.constructor = Child;
6
}

这个inherits()函数可以复用:
function Student(props) {
this.name = props.name || 'Unnamed';
} Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
} function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
} // 实现原型继承链:
inherits(PrimaryStudent, Student); // 绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
20
 
1
function Student(props) {
2
    this.name = props.name || 'Unnamed';
3
}
4

5
Student.prototype.hello = function () {
6
    alert('Hello, ' + this.name + '!');
7
}
8

9
function PrimaryStudent(props) {
10
    Student.call(this, props);
11
    this.grade = props.grade || 1;
12
}
13

14
// 实现原型继承链:
15
inherits(PrimaryStudent, Student);
16

17
// 绑定其他方法到PrimaryStudent原型:
18
PrimaryStudent.prototype.getGrade = function () {
19
    return this.grade;
20
};

所以原型集成的实现方式就是:
  • 定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this
  • 借助中间函数F实现原型链继承,最好通过封装的inherits函数完成
  • 继续在新的构造函数的原型上定义新方法


2、class继承(ES6)

class 这个新的关键字从ES6正式引入到JS中,目的就是为了让“类”的定义变得简单:

用 class 写“构造函数”(或者说类?)是这样:

class Student {
// 定义构造函数
constructor(name) {
this.name = name;
} //定义在原型上的函数,没有function关键字,相当于 Student.prototype.hello = function(){...}
hello() {
alert('Hello, ' + this.name + '!');
}
}
11
 
1
class Student {
2
    // 定义构造函数
3
    constructor(name) {
4
        this.name = name;
5
    }
6

7
    //定义在原型上的函数,没有function关键字,相当于 Student.prototype.hello = function(){...}
8
    hello() {
9
        alert('Hello, ' + this.name + '!');
10
    }
11
}

然后创建一个Student对象的方式没有改变:

var xiaoming = new Student('小明');
xiaoming.hello();
2
 
1
var xiaoming = new Student('小明');
2
xiaoming.hello();

而 class 继承,也不需要像之前写原型继承的那种方式那么复杂了(当然,本质上和原来并没有区别),可以直接通过关键字 extends 实现:

class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
} myGrade() {
alert('I am at grade ' + this.grade);
}
}
x
 
1
class PrimaryStudent extends Student {
2
    constructor(name, grade) {
3
        super(name); // 记得用super调用父类的构造方法!
4
        this.grade = grade;
5
    }
6

7
    myGrade() {
8
        alert('I am at grade ' + this.grade);
9
    }
10
}

好了,class 继承就到这里了,学过Java的同学再看这个,会觉得几乎就是类似的写法,用起来很简单,当然,本质上还是要去理解原型继承才是重点。


04面向对象编程-02-原型继承 和 ES6的class继承的更多相关文章

  1. 04面向对象编程-01-创建对象 和 原型理解(prototype、__proto__)

    1.JS中对象的"不同":原型概念 从Java中我们可以很好地去理解 "类" 和 "实例" 两个概念,可是在JavaScript中,这个概念 ...

  2. Javascript面向对象编程(三):非构造函数的继承(对象的深拷贝与浅拷贝)

    Javascript面向对象编程(三):非构造函数的继承   作者: 阮一峰 日期: 2010年5月24日 这个系列的第一部分介绍了"封装",第二部分介绍了使用构造函数实现&quo ...

  3. 使用类进行面向对象编程 Class 实例化 和 ES5实例化 对比,继承

    ES5 写法 function Book(title, pages, isbn) { this.title = title; this.pages = pages; this.isbn = isbn; ...

  4. es5继承和es6类和继承

    es6新增关键字class,代表类,其实相当于代替了es5的构造函数 通过构造函数可以创建一个对象实例,那么通过class也可以创建一个对象实列 /* es5 创建一个person 构造函数 */ f ...

  5. python04 面向对象编程02

    为啥要用类而不用函数呢 记住两个原则: 减少重复代码 代码会经常变更 2    会对变量或字符串的合法性检测(在实例初始化的时候能够统一初始化各个实例的变量,换做函数来说,要弄出同样的变量那么在初始化 ...

  6. Javascript面向对象编程(三):非构造函数的继承 by 阮一峰

    今天是最后一个部分,介绍不使用构造函数实现"继承". 一.什么是"非构造函数"的继承? 比如,现在有一个对象,叫做"中国人". var Ch ...

  7. (转)Javascript面向对象编程(三):非构造函数的继承(作者:阮一峰)

    不使用构造函数实现"继承". 一.什么是"非构造函数"的继承? 比如,现在有一个对象,叫做"中国人". var Chinese = { na ...

  8. Javascript面向对象编程(三):非构造函数的继承

    转载自:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance_continued.html 一.什 ...

  9. JS面向对象编程(三):非构造函数的继承

    一.什么是"非构造函数"的继承?            现在有一个对象,叫"中国人".            var Chinese = {           ...

随机推荐

  1. 命令行创建Maven项目卡住以及出错解决办法。

    第一次通过命令行创建maven项目.结果,果不其然啊,还是出问题了,不过出问题比没有出问题强,知道哪里有问题并学会解决也是一种收获. 遇到的第一个问题,在从仓库下载东西的时候会卡住,我开始以为是网速问 ...

  2. MySql分库分表总结(转)

    为什么要分库分表 可以用说用到MySQL的地方,只要数据量一大, 马上就会遇到一个问题,要分库分表. 这里引用一个问题为什么要分库分表呢?MySQL处理不了大的表吗? 其实是可以处理的大表的.我所经历 ...

  3. 【Ubuntu 16】安装eclipse

    1.将eclipse.tar.gz传送到/home/xxx/下,解压缩,这里我已经配置好了JDK1.7,所以eclipse配置了就可以使用 2.创建快捷方式 dream361@master:~$ to ...

  4. poj 2528 poster经典线段树+lazy+离散化

    #include<cstdio> #include<cstring> #include<algorithm> using namespace std; ; #def ...

  5. PowerShell 脚本执行策略

    为防止恶意脚本的执行,PowerShell 中设计了一个叫做执行策略(Execution Policy)的东西(我更倾向于把它叫做脚本执行策略).我们可以在不同的应用场景中设置不同的策略来防止恶意脚本 ...

  6. javaSE基础之 LinkedList的底层简单实现

    这里贴上LinkedList底层的简单实现 package com.yck.mylinkedlist; public class Node { private Node previous; //上一结 ...

  7. C++ 将函数作为形参

    今天偶然看到一段代码,其中将函数作为形参进行设计,一开始不理解,自己试了一下,发现果然可行 #include <iostream> using namespace std; void vi ...

  8. JavaScript学习日志(二):面向对象的程序设计

    1,ECMAScript不像其他面向对象的语言那样有类的概念,它的对象与其他不同. 2,ECMAScript有两种属性:数据属性和访问器属性.([[]]这种双中括号表示属性为内部属性,外部不可直接访问 ...

  9. 在数组a中,a[i]+a[j]=a[k],求a[k]的最大值,a[k]max——猎八哥fly

    在数组a中,a[i]+a[j]=a[k],求a[k]的最大值,a[k]max. 思路:将a中的数组两两相加,组成一个新的数组.并将新的数组和a数组进行sort排序.然后将a数组从大到小与新数组比较,如 ...

  10. mysql 5.7 Warning: Using a password on the command line interface can be insecure. 解决方案

    百度了好多,发现都是lunix环境下的,没有找到windows和OS 的,在lunix环境下的解决方案一般就是修改数据库配置文件 my.conf 在Windows 中是没有my.cnf 文件,而是叫做 ...