Home  >  Article  >  Web Front-end  >  Let you thoroughly understand the principles of Javascript inheritance!

Let you thoroughly understand the principles of Javascript inheritance!

不言
不言forward
2018-09-28 17:21:412466browse

The content this article brings to you is to help you thoroughly understand the principles of Javascript inheritance! It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Before understanding inheritance, you need to know three things about js:

  1. What is the JS prototype chain

  2. this What is the value

  3. What does new in JS do

1. What is the JS prototype chain?

We know that JS has objects, such as

    var obj = { name: 'obj' }

We print out obj through the console:

Let you thoroughly understand the principles of Javascript inheritance!

We will find that obj already has several properties (methods). Then the question comes: Where does valueOf / toString / constructor come from? We did not assign a value to obj.valueOf.

The above picture is a bit difficult to understand. I drew a schematic diagram by hand:

Let you thoroughly understand the principles of Javascript inheritance!

We found that the console typed The result is:

  1. obj itself has an attribute name (this is what we added to it)

  2. obj also has an attribute called __proto__ (It is an object)

  3. obj also has an attribute, including valueOf, toString, constructor, etc.

  4. obj.__proto__ actually also has one The attribute called __proto__ (console.log is not shown), the value is null

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

Answer: This is related to __proto__.

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

  1. See if the obj object itself has a toString attribute. If not, go to the next step.

  2. Look at whether the obj.__proto__ object has a toString attribute, and found that obj.__proto__ has a toString attribute, so I found it, so obj.toString is actually the obj.__proto__ found in step 2. .toString.

  3. If obj.__proto__ does not exist, the browser will continue to view obj.__proto__.__proto__

  4. If obj.__proto__.__proto__ also If not, the browser will continue to check obj.__proto__.__proto__.__proto__

##5 until toString is found or

proto is null.

The above process is the "search process" of "reading" attributes. And this "search process" is connected to the chain composed of

proto. This chain is called the "prototype chain".

Shared prototype chain

Now we have another object

var obj2 = { name: 'obj2' }
As shown:

Let you thoroughly understand the principles of Javascript inheritance!

Then obj.toString and obj2.toString are actually the same thing, that is, obj2.__proto__.toString.

To put it bluntly, if we change one of them __proto__.toString, then the other one will actually change!

Differentiation

If we want obj.toString and obj2.toString What to do if your behavior is different?

Just assign the value directly:

obj.toString = function(){ return '新的 toString 方法' }

Let you thoroughly understand the principles of Javascript inheritance!

##Summary

    [Read] When properties are read, the prototype chain will be searched
  1. [New] When properties are added, the prototype chain will not be looked at
  2. 2. this What is the value of

You may have encountered this JS interview question:

var obj = {
  foo: function(){
    console.log(this)
  }
}

var bar = obj.foo
obj.foo() // 打印出的 this 是 obj
bar() // 打印出的 this 是 window

Please explain why the values ​​of the functions in the last two lines are different.

Function call

There are three function call forms in JS (ES5):

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

Generally, beginners know the first two forms, and think that the first two forms " Better than the third form.

Our teacher Fang Fang’s grandma said that you must remember that the third calling form is the normal calling form:

    func.call(context, p1, p2)

The other two are syntax sugar and can be changed equivalently It is in the form of call:

func(p1, p2) is equivalent to func.call(undefined, p1, p2);

obj.child.method(p1, p2) is equivalent to obj .child.method.call(obj.child, p1, p2);

So far our function call has only one form:

func.call(context, p1, p2)

In this way, this can be easily explained

This is the context above. This is the context passed when you call a function. Since you never use the call form of function call, you never know it.

Let’s first look at how to determine this in func(p1, p2):

当你写下面代码时

function func(){
  console.log(this)
}

func()
等价于

function func(){
  console.log(this)
}

func.call(undefined) // 可以简写为 func.call()

Logically speaking, the printed this should be undefined, but there is a rule in the browser:

如果你传的 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 又是什么呢?

我们可以把 arr0 想象为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<p>哎呀,看起来好简单</p><h4>质疑</h4><p>上面的代码存在一个问题:浪费了很多内存</p><ol class=" list-paddingleft-2">
<li><p>行走、奔跑、死亡、攻击、防御这五个动作对于每个士兵其实是一样的,只需要各自引用同一个函数就可以了,没必要重复创建 100 个行走、100个奔跑……</p></li>
<li><p>这些士兵的兵种和攻击力都是一样的,没必要创建 100 次。</p></li>
<li><p>只有 ID 和生命值需要创建 100 次,因为每个士兵有自己的 ID 和生命值。</p></li>
</ol><h4>改进</h4><p>通过第一节可以知道 ,我们可以通过原型链来解决重复创建的问题:我们先创建一个「士兵原型」,然后让「士兵」的 <strong>proto</strong> 指向「士兵原型」。</p><pre class="brush:php;toolbar:false">var 士兵原型 = {
  兵种:"美国大兵",
  攻击力:5,
  行走:function(){ /*走俩步的代码*/},
  奔跑:function(){ /*狂奔的代码*/  },
  死亡:function(){ /*Go die*/    },
  攻击:function(){ /*糊他熊脸*/   },
  防御:function(){ /*护脸*/       }
}

var 士兵们 = []
var 士兵
for(var i=0; i<h4>优雅?</h4><p>有人指出创建一个士兵的代码分散在两个地方很不优雅,于是我们用一个函数把这两部分联系起来:</p><pre class="brush:php;toolbar:false">function 士兵(ID){
  var 临时对象 = {};
  临时对象.__proto__ = 士兵.原型;
  临时对象.ID = ID;
  临时对象.生命值 = 42;
  
  return 临时对象;
}  

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

// 保存为文件:士兵.js

 然后就可以愉快地引用「士兵」来创建士兵了:

var 士兵们 = []
for(var i=0; i<p>JS 之父看到大家都这么搞,觉得何必呢,我给你们个糖吃,于是 JS 之父创建了 new 关键字,可以让我们少写几行代码:</p><p style="text-align: center;"><span class="img-wrap"><img src="https://img.php.cn//upload/image/223/671/797/1538126235427481.png" title="1538126235427481.png" alt="Let you thoroughly understand the principles of Javascript inheritance!"></span></p><p><strong>只要你在士兵前面使用 new 关键字,那么可以少做四件事情:</strong></p><ol class=" list-paddingleft-2">
<li><p>不用创建临时对象,因为 new 会帮你做(你使用「this」就可以访问到临时对象);</p></li>
<li><p>不用绑定原型,因为new 会帮你做(new 为了知道原型在哪,所以指定原型的名字 prototype);</p></li>
<li><p>不用 return 临时对象,因为 new 会帮你做;</p></li>
<li><p>不要给原型想名字了,因为 new 指定名字为 prototype。</p></li>
</ol><h4>这一次用 new 来写</h4><pre class="brush:php;toolbar:false">function 士兵(ID){
  this.ID = ID
  this.生命值 = 42
}

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

// 保存为文件:士兵.js
然后是创建士兵(加了一个 new 关键字):

var 士兵们 = []
for(var i=0; i<p><strong>new 的作用,就是省那么几行代码。(也就是所谓的语法糖)</strong></p><h4>注意 constructor 属性</h4><p>new 操作为了记录「临时对象是由哪个函数创建的」,所以预先给「士兵.prototype」加了一个 constructor 属性:</p><pre class="brush:php;toolbar:false">士兵.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);

打印结果:

Let you thoroughly understand the principles of Javascript inheritance!

这个主要是借用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();

打印:

Let you thoroughly understand the principles of Javascript inheritance!

通过一讲的,我们知道要共享莫些属性,需要 对象.__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)

打印:

Let you thoroughly understand the principles of Javascript inheritance!

将 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 一次父类。其实这种方法还是有问题的,如果我在控制台打印以下两句:

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

Let you thoroughly understand the principles of Javascript inheritance!

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

组合继承的优化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

那大家可能说这样解决了吗,其实没有解决,因为这时 Child5.prototype 还是没有自己的 constructor,它要找的话还是向自己的原型对象上找最后还是找到  Parent5.prototype, constructor还是 Parent5 ,所以要给 Child5.prototype 写自己的 constructor:

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

The above is the detailed content of Let you thoroughly understand the principles of Javascript inheritance!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete