Javascript基础-原型和原型链

理解原型设计模式以及 JavaScript 中的原型规则

原型链:每一个实例对象都有一个__proto__属性(隐式原型),在js内部用来查找原型链;每一个构造函数都有prototype属性(显示原型),用来显示修改对象的原型,实例.__proto__=构造函数.prototype=原型。原型链的特点就是:通过实例.__proto__查找原型上的属性,从子类一直向上查找对象原型的属性,继而形成一个查找链即原型链。

instanceof 的底层实现原理,手动实现一个 instanceof

简单说就是判断实例对象的__proto__是不是强等于对象的prototype属性,如果不是继续往原型链上找,直到 __proto__null 为止。

1
2
3
4
5
6
7
8
9
10
11
12
13

//obj 表示实例对象,object 表示对象
function instanceOf(obj, object) {
var O = object.prototype;
obj = obj.__proto__;
while (true) {
if (obj === null)
return false;
if (O === obj) // 这里重点:当 O 严格等于 obj 时,返回 true
return true;
obj = obj.__proto__;
}
}

理解 JavaScript 的执行上下文栈,可以应用堆栈信息快速定位问题

执行上下文 就是当前 JavaScript 代码被解析和执行时所在环境的抽象概念, JavaScript 中运行任何的代码都是在执行上下文中运行。

执行上下文总共有三种类型:全局执行上下文, 函数执行上下文, Eval 函数执行上下文

执行栈,在其他编程语言中也被叫做调用栈,具有 LIFO(后进先出)结构,用于存储在代码执行期间创建的所有执行上下文。

实现继承的几种方式以及他们的优缺点

1.原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//父类,带属性
function Super(){
this.flag = true;
}
//为了提高复用性,方法绑定在父类原型属性上
Super.prototype.getFlag = function(){
return this.flag;
}
//来个子类
function Sub(){
this.subFlag = false;
}
//实现继承
Sub.prototype = new Super;
//给子类添加子类特有的方法,注意顺序要在继承之后
Sub.prototype.getSubFlag = function(){
return this.subFlag;
}
//构造实例
var es5 = new Sub;

缺点:构造函数原型上的属性在所有该构造函数构造的实例上是共享的,即属性没有私有化,原型上属性的改变会作用到所有的实例上。

2.构造函数继承
在构造子类构造函数时内部使用call或apply来调用父类的构造函数

1
2
3
4
5
6
7
8
9
10
11

function Super(){
this.flag = true;
}
function Sub(){
Super.call(this) //如果父类可以需要接收参数,这里也可以直接传递
}
var obj = new Sub();
obj.flag = flase;
var obj_2 = new Sub();
console.log(obj.flag) //依然是true,不会相互影响

优缺点:实现了属性的私有化,但是子类无法访问父类原型上的属性。

3.组合继承
利用构造函数和原型链的方法,可以比较完美的实现继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

function Super(){
this.flag = true;
}
Super.prototype.getFlag = function(){
return this.flag; //继承方法
}
function Sub(){
this.subFlag = flase
// 第一次调用父类构造函数
Super.call(this) //继承属性
}
// 第二次调用父类构造函数
Sub.prototype = new Super;
var obj = new Sub();
Sub.prototype.constructor = Sub;

这里还有个小问题,Sub.prototype = new Super; 会导致Sub.prototypeconstructor指向Super;然而constructor的定义是要指向原型属性对应的构造函数的,Sub.prototypeSub构造函数的原型,所以应该添加一句纠正:Sub.prototype.constructor = Sub;

4.寄生继承
即将Sub.prototype=new Super改为Sub.prototype=Object.create(Supper.prototype),避免了组合继承中构造函数调用了两次的弊端。

可以描述 new 一个对象的详细过程,手动实现一个 new 操作符

过程
当我们new一个构造函数,得到的实例继承了构造器的构造属性以及原型上的属性。
在《JavaScript模式》这本书中,new的过程说的比较直白,当我们new一个构造器,主要有三步:
1.以构造器的prototype属性为原型,创建新对象;
2.将this(也就是上一句中的新对象)和调用参数传给构造器,执行;
3.如果构造器没有手动返回对象,则返回第一步创建的对象

实现

1
2
3
4
5
function myNew(Obj,...args){
var obj = Object.create(Obj.prototype);// 使用指定的原型对象及其属性去创建一个新的对象
Obj.apply(obj,args); // 绑定 this 到obj, 设置 obj 的属性
return obj; // 返回实例
}

理解 es6 class 构造以及继承的底层实现原理

ES6中通过class关键字,定义类

1
2
3
4
5
6
7
8
9
class Parent {
constructor(name,age){
this.name = name;
this.age = age;
}
speakSomething(){
console.log("I can speek chinese");
}
}

经过babel转码之后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}

return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();

function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}

var Parent = function () {
function Parent(name, age) {
_classCallCheck(this, Parent);

this.name = name;
this.age = age;
}

_createClass(Parent, [{
key: "speakSomething",
value: function speakSomething() {
console.log("I can speek chinese");
}
}]);

return Parent;
}();

可以看到ES6类的底层还是通过构造函数去创建的。

通过ES6创建的类,是不允许你直接调用的。在ES5中,构造函数是可以直接运行的,比如Parent()。但是在ES6就不行。我们可以看到转码的构造函数中有_classCallCheck(this, Parent)语句,这句话是防止你通过构造函数直接运行的。你直接在ES6运行Parent(),这是不允许的,ES6中抛出Class constructor Parent cannot be invoked without 'new'错误。转码后的会抛出Cannot call a class as a function.我觉得这样的规范挺好的,能够规范化类的使用方式。

转码中_createClass方法,它调用Object.defineProperty方法去给新创建的Parent添加各种属性。defineProperties(Constructor.prototype, protoProps)是给原型添加属性。如果你有静态属性,会直接添加到构造函数上defineProperties(Constructor, staticProps)。但是貌似并没有用到,下面可以证明.

这两个流程走下来,其实就创建了一个类。

上面讲的是创建一个类的过程,那ES6如何实现继承的呢?还是上面的例子,这次我们给Parent添加静态属性,原型属性,内部属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Parent {
static height = 12
constructor(name,age){
this.name = name;
this.age = age;
}
speakSomething(){
console.log("I can speek chinese");
}
}
Parent.prototype.color = 'yellow'


//定义子类,继承父类
class Child extends Parent {
static width = 18
constructor(name,age){
super(name,age);
}
coding(){
console.log("I can code JS");
}
}

var c = new Child("job",30);
c.coding()

转码之后的代码变成了这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}

return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();

function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}

function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}

var Parent = function () {
function Parent(name, age) {
_classCallCheck(this, Parent);

this.name = name;
this.age = age;
}

_createClass(Parent, [{
key: "speakSomething",
value: function speakSomething() {
console.log("I can speek chinese");
}
}]);

return Parent;
}();

Parent.height = 12;

Parent.prototype.color = 'yellow';

//定义子类,继承父类

var Child = function (_Parent) {
_inherits(Child, _Parent);

function Child(name, age) {
_classCallCheck(this, Child);

return _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, name, age));
}

_createClass(Child, [{
key: "coding",
value: function coding() {
console.log("I can code JS");
}
}]);

return Child;
}(Parent);

Child.width = 18;


var c = new Child("job", 30);
c.coding();

我们可以看到,构造类的方法都没变,只是添加了_inherits核心方法来实现继承,下面我们就看下这个方法做了什么?

首先是判断父类的类型,然后

1
2
3
4
5
6
7
8
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});

这段代码翻译下来就是

1
2
3
4
function F(){}
F.prototype = superClass.prototype
subClass.prototype = new F()
subClass.prototype.constructor = subClass

接下来subClass.proto = superClass
_inherits核心思想就是下面两句

1
2
subClass.prototype.__proto__ = superClass.prototype
subClass.__proto__ = superClass

一图胜千言

那为什么这样一倒腾,它就实现了继承了呢?
首先 subClass.prototype.__proto__ = superClass.prototype保证了c instanceof Parenttrue,Child的实例可以访问到父类的属性,包括内部属性,以及原型属性。其次,subClass.__proto__ = superClass,保证了Child.height也能访问到,也就是静态方法。

subClass.__proto__ = superClass不是很好理解,可以通过下面的方式理解

1
2
3
function A(){}
var a = new A()
a.__proto__ = A.prototype

a是一个实例,A.prototype是构造方法的原型。通过这种方式,那么a就可以访问A.prototype上面的方法。

那把 subClass类比成 a,superClass类比成A.prototype,那是不是subClass可以直接访问 superClass的静态属性,静态方法了。

参考资料: ES6类以及继承的实现原理