First, before understanding inheritance, we need to know three things of js:

  1. What is JS prototype chain

  2. What is the value of this in the end

  3. JS's new in the end is doing

First, what is JS prototype chain?

We know that there are JS objects, such as

    var obj = { name: 'obj' }

We obj print out the console:


1


We will find that  objalready has several attributes (methods) a. So the question is: valueOf/toString/constructor how come? We do not have to  obj.valueOf assign it.

Above this figure a little difficult to understand, a schematic diagram of hand-painted:


1


We found that the console is to play out the results:

  1. obj itself has a property name (which we added to it)

  2. obj there is a property called  proto (it is an object)

  3. Another obj property, including valueOf, toString, constructor, etc.

  4. obj .__ proto__ actually have a property called __proto__ (the console.log not shown), the value is null

Now back to our question: Why obj will have valueOf / toString / constructor these attributes?

The answer: This is related to __proto__.

When we 'read' obj.toString, JS engine will do the following things:

  1. To see  obj the object itself has no  toString property. I did not went to the next step.

  2. See if  obj.__proto__ objects have no  toString attributes found  obj.__proto__ there  toString property, then found, it  obj.toStringis in fact found in step 2  obj.__proto__.toString.

  3. If  obj.__proto__not, then the browser will continue to view  obj.__proto__.__proto__.

  4. 如果 obj.__proto__.__proto__ 也没有,那么浏览器会继续查看 obj.__proto__.__proto__.__proto__

5.直到找到 toString 或者 __proto__ 为 null

上面的过程,就是「读」属性的「搜索过程」。而这个「搜索过程」,是连着由 proto 组成的链子一直走的。这个链子,就叫做「原型链」。

共享原型链

现在我们还有另一个对象

var obj2 = { name: 'obj2' } 复制代码

如图:


1


那么 obj.toString 和 obj2.toString 其实是同一东西, 也就是 obj2.__proto__.toString。 说白了,我们改其中的一个 __proto__.toString ,那么另外一个其实也会变!

差异化

如果我们想让 obj.toString 和 obj2.toString 的行为不同怎么做呢? 直接赋值就好了:

obj.toString = function(){ return '新的 toString 方法' }     复制代码


1


小结

  1. [读]属性时会沿着原型链搜索

  2. [新增]属性时不会去看原型链

二、 this 的值到底是什么

你可能遇到过这样的 JS 面试题:

var obj = {   foo: function(){     console.log(this)   } } var bar = obj.foo obj.foo() // 打印出的 this 是 obj bar() // 打印出的 this 是 window

请解释最后两行函数的值为什么不一样。

函数调用

JS(ES5)里面有三种函数调用形式:

func(p1, p2)  obj.child.method(p1, p2) func.call(context, p1, p2) // 先不讲 apply 复制代码

一般,初学者都知道前两种形式,而且认为前两种形式「优于」第三种形式。

我们方方老师大姥说了,你一定要记住,第三种调用形式,才是正常调用形式:

    func.call(context, p1, p2) 复制代码

其他两种都是语法糖,可以等价地变为 call 形式:

func(p1, p2)等价于 func.call(undefined, p1, p2);

obj.child.method(p1, p2) 等价于 obj.child.method.call(obj.child, p1, p2);

至此我们的函数调用只有一种形式:

func.call(context, p1, p2) 复制代码

这样,this 就好解释了 this就是上面 context

this 是你 call 一个函数时传的 context,由于你从来不用 call 形式的函数调用,所以你一直不知道。

先看 func(p1, p2) 中的 this 如何确定:

当你写下面代码时 function func(){   console.log(this) } func() 等价于 function func(){   console.log(this) } func.call(undefined) // 可以简写为 func.call()

按理说打印出来的 this 应该就是 undefined 了吧,但是浏览器里有一条规则:

如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)

因此上面的打印结果是 window。如果你希望这里的 this 不是 window,很简单:

func.call(obj) // 那么里面的 this 就是 obj 对象了      复制代码

回到题目:

var obj = {   foo: function(){     console.log(this)   } } var bar = obj.foo obj.foo() // 转换为 obj.foo.call(obj),this 就是 obj bar()  // 转换为 bar.call() // 由于没有传 context // 所以 this 就是 undefined // 最后浏览器给你一个默认的 this —— window 对象

[ ] 语法

function fn (){ console.log(this) } var arr = [fn, fn2] arr[0]() // 这里面的 this 又是什么呢?  复制代码

我们可以把 arr[0]( ) 想象为arr.0( ),虽然后者的语法错了,但是形式与转换代码里的 obj.child.method(p1, p2) 对应上了,于是就可以愉快的转换了:

        arr[0]()  假想为    arr.0() 然后转换为 arr.0.call(arr) 那么里面的 this 就是 arr 了 复制代码

小结:

  1. this 就是你 call 一个函数时,传入的第一个参数。

  2. 如果你的函数调用不是 call 形式, 请将其转换为 call 形式

三、JS 的 new 到底是干什么的?

我们声明一个士兵,具有如下属性:

var 士兵 = {   ID: 1, // 用于区分每个士兵   兵种:"美国大兵",   ***力:5,   生命值:42,    行走:function(){ /*走俩步的代码*/},   奔跑:function(){ /*狂奔的代码*/  },   死亡:function(){ /*Go die*/    },   ***:function(){ /*糊他熊脸*/   },   防御:function(){ /*护脸*/       } }

我们制造一个士兵, 只需要这样:

兵营.制造(士兵)            复制代码

如果需要制造 100 个士兵怎么办呢?

循环 100 次吧: var 士兵们 = [] var 士兵 for(var i=0; i<100; i++){   士兵 = {     ID: i, // ID 不能重复     兵种:"美国大兵",     ***力:5,     生命值:42,      行走:function(){ /*走俩步的代码*/},     奔跑:function(){ /*狂奔的代码*/  },     死亡:function(){ /*Go die*/    },     ***:function(){ /*糊他熊脸*/   },     防御:function(){ /*护脸*/       }   }   士兵们.push(士兵) } 兵营.批量制造(士兵们)

哎呀,看起来好简单

质疑

上面的代码存在一个问题:浪费了很多内存

  1. 行走、奔跑、死亡、***、防御这五个动作对于每个士兵其实是一样的,只需要各自引用同一个函数就可以了,没必要重复创建 100 个行走、100个奔跑……

  2. 这些士兵的兵种和***力都是一样的,没必要创建 100 次。

  3. 只有 ID 和生命值需要创建 100 次,因为每个士兵有自己的 ID 和生命值。

####改进

通过第一节可以知道 ,我们可以通过原型链来解决重复创建的问题:我们先创建一个「士兵原型」,然后让「士兵」的 proto 指向「士兵原型」。

var 士兵原型 = {   兵种:"美国大兵",   ***力:5,   行走:function(){ /*走俩步的代码*/},   奔跑:function(){ /*狂奔的代码*/  },   死亡:function(){ /*Go die*/    },   ***:function(){ /*糊他熊脸*/   },   防御:function(){ /*护脸*/       } } var 士兵们 = [] var 士兵 for(var i=0; i<100; i++){   士兵 = {     ID: i, // ID 不能重复     生命值:42   }   /*实际工作中不要这样写,因为 __proto__ 不是标准属性*/   士兵.__proto__ = 士兵原型    士兵们.push(士兵) } 兵营.批量制造(士兵们) 复制代码

优雅?

有人指出创建一个士兵的代码分散在两个地方很不优雅,于是我们用一个函数把这两部分联系起来:

function 士兵(ID){   var 临时对象 = {};   临时对象.__proto__ = 士兵.原型;   临时对象.ID = ID;   临时对象.生命值 = 42;      return 临时对象; }   士兵.原型 = {   兵种:"美国大兵",   ***力:5,   行走:function(){ /*走俩步的代码*/},   奔跑:function(){ /*狂奔的代码*/  },   死亡:function(){ /*Go die*/    },   ***:function(){ /*糊他熊脸*/   },   防御:function(){ /*护脸*/       } } // 保存为文件:士兵.js  然后就可以愉快地引用「士兵」来创建士兵了: var 士兵们 = [] for(var i=0; i<100; i++){   士兵们.push(士兵(i)) } 兵营.批量制造(士兵们) 复制代码

JS 之父看到大家都这么搞,觉得何必呢,我给你们个糖吃,于是 JS 之父创建了 new 关键字,可以让我们少写几行代码:


1


只要你在士兵前面使用 new 关键字,那么可以少做四件事情:

  1. 不用创建临时对象,因为 new 会帮你做(你使用「this」就可以访问到临时对象);

  2. 不用绑定原型,因为new 会帮你做(new 为了知道原型在哪,所以指定原型的名字 prototype);

  3. 不用 return 临时对象,因为 new 会帮你做;

  4. 不要给原型想名字了,因为 new 指定名字为 prototype

这一次用 new 来写

function 士兵(ID){   this.ID = ID   this.生命值 = 42 } 士兵.prototype = {   兵种:"美国大兵",   ***力:5,   行走:function(){ /*走俩步的代码*/},   奔跑:function(){ /*狂奔的代码*/  },   死亡:function(){ /*Go die*/    },   ***:function(){ /*糊他熊脸*/   },   防御:function(){ /*护脸*/       } } // 保存为文件:士兵.js 然后是创建士兵(加了一个 new 关键字): var 士兵们 = [] for(var i=0; i<100; i++){   士兵们.push(new 士兵(i)) } 兵营.批量制造(士兵们)

new 的作用,就是省那么几行代码。(也就是所谓的语法糖)

注意 constructor 属性

new 操作为了记录「临时对象是由哪个函数创建的」,所以预先给「士兵.prototype」加了一个 constructor 属性:

士兵.prototype = {   constructor: 士兵 } 复制代码

如果你重新对「士兵.prototype」赋值,那么这个 constructor 属性就没了,所以你应该这么写:

士兵.prototype.兵种 = "美国大兵" 士兵.prototype.***力 = 5 士兵.prototype.行走 = function(){ /*走俩步的代码*/} 士兵.prototype.奔跑 = function(){ /*狂奔的代码*/  } 士兵.prototype.死亡 = function(){ /*Go die*/    } 士兵.prototype.*** = function(){ /*糊他熊脸*/   } 士兵.prototype.防御 = function(){ /*护脸*/       }

或者你也可以自己给 constructor 重新赋值:

士兵.prototype = {   constructor: 士兵,   兵种:"美国大兵",   ***力:5,   行走:function(){ /*走俩步的代码*/},   奔跑:function(){ /*狂奔的代码*/  },   死亡:function(){ /*Go die*/    },   ***:function(){ /*糊他熊脸*/   },   防御:function(){ /*护脸*/       } }

四、继承

继承的本质就是上面的讲的原型链

1)借助构造函数实现继承

 function Parent1() {    this.name = 'parent1';  }    Parent1.prototype.say = function () {}    function Child1() {    Parent1.call(this);    this.type = 'child';  }  console.log(new Child1);

打印结果:


1


这个主要是借用call 来改变this的指向,通过 call 调用 Parent ,此时 Parent 中的 this 是指 Child1。有个缺点,从打印结果看出 Child1并没有say方法,所以这种只能继承父类的实例属性和方法,不能继承原型属性/方法。

2)借助原型链实现继承

/**  * 借助原型链实现继承  */ function Parent2() {   this.name = 'parent2';   this.play = [1, 2, 3]; } function Child2() {   this.type = 'child2'; } Child2.prototype = new Parent2(); console.log(new Child2); var s1 = new Child2(); var s2 = new Child2();

打印:


1


通过一讲的,我们知道要共享莫些属性,需要 对象.__proto__ = 父亲对象的.prototype,但实际上我们是不能直接 操作__proto__,这时我们可以借用 new 来做,所以 Child2.prototype = new Parent2(); <=> Child2.prototype.__proto__ = Parent2.prototype; 这样我们借助 new 这个语法糖,就可以实现原型链继承。但这里有个总是,如打印结果,我们给 s1.play新增一个值 ,s2也跟着改了。所以这个是原型链继承的缺点,原因是 s1.__pro__ 和 s2.__pro__指向同一个地址即 父类的prototype

3)组合方式实现继承

/**  * 组合方式  */ function Parent3() {   this.name = 'parent3';   this.play = [1, 2, 3]; } Parent3.prototype.say = function () { } function Child3 () {   Parent3.call(this);   this.type = 'child3'; } Child3.prototype = new Parent3(); var s3 = new Child3(); var s4 = new Child3(); s3.play.push(4); console.log(new Child3); console.log(s3.play, s4.play)

打印:


1


将 1 和 2 两种方式组合起来,就可以解决1和2存在问题,这种方式为组合继承。这种方式有点缺点就是我实例一个对象的时, 父类 new 了两次,一次是var s3 = new Child3()对应 Child3.prototype = new Parent3()还要new 一次。

4)组合继承的优化1

function Parent4() {   this.name = 'parent4';   this.play = [1, 2, 3]; } Parent4.prototype.say = function () { } function Child4() {   Parent4.call(this);   this.type = 'child4'; } Child4.prototype = Parent4.prototype; var s5 = new Child4(); var s6 = new Child4();

这边主要为 Child4.prototype = Parent4.prototype, 因为我们通过构造函数就可以拿到所有属性和实例的方法,那么现在我想继承父类的原型对象,所以你直接赋值给我就行,不用在去 new 一次父类。其实这种方法还是有问题的,如果我在控制台打印以下两句:



从打印可以看出,此时我是没有办法区分一个对象 是直接 由它的子类实例化还是父类呢?我们还有一个方法判断来判断对象是否是类的实例,那就是用 constructor,我在控制台打印以下内容:



咦,你会发现它指向的是父类 ,这显然不是我们想要的结果, 上面讲过我们 prototype里面有一个 constructor, 而我们此时子类的 prototype 指向是 父类的 prototye ,而父类prototype里面的contructor当然是父类自己的,这个就是产生该问题的原因。

5)组合继承的优化2

/**  * 组合继承的优化2  */ function Parent5() {   this.name = 'parent4';   this.play = [1, 2, 3]; } Parent5.prototype.say = function () { } function Child5() {   Parent5.call(this);   this.type = 'child4'; } Child5.prototype = Object.create(Parent5.prototype);

这里主要使用Object.create(),它的作用是将对象继承到__proto__属性上。举个例子:

var test = Object.create({x:123,y:345}); console.log(test);//{} console.log(test.x);//123 console.log(test.__proto__.x);//3 console.log(test.__proto__.x === test.x);//true

That we may say that solved it, in fact, not been resolved, because then Child5.prototype still do not own a constructor, it would still looking to finally find on their own prototype object or find Parent5.prototype, constructor or Parent5, so to Child5.prototype to write your own constructor:

Child5.prototype = Object.create(Parent5.prototype); Child5.prototype.constructor = Child5;