Home > Web Front-end > JS Tutorial > body text

Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain

php是最好的语言
Release: 2018-08-01 09:37:54
Original
1513 people have browsed it

Why can't I use objects on the prototype chain? And what is the underlying principle of the JS prototype chain?

When you first come into contact with the JS prototype chain, you will come into contact with a familiar term: prototype; if you have ever gone deep into prototype, you will come into contact with it Another noun: __proto__ (note: there are two underlines on both sides, not one). The following will be explained around the two terms prototype and __proto__

 1. Why objects cannot be used on the prototype chain:

Let’s take a very simple example first. I have a class called Humans (human beings), and then I have an object called Tom (a person) and another object called Merry (another person). Obviously Tom and Merry are obtained after instantiating the Humans class. Then this example can be written as the following code:

function Humans() {
    this.foot = 2;
}
Humans.prototype.ability = true;var Tom = new Humans();var Merry = new Humans();

console.log(Tom.foot);//结果:2console.log(Tom.ability);//结果:trueconsole.log(Merry.foot);//结果:2console.log(Merry.ability);//结果:true
Copy after login

The above is a very simple object-oriented example. I believe everyone can understand it. If you try Modify Tom's ability attribute, then

function Humans() {
    this.foot = 2;
}
Humans.prototype.ability = true;var Tom = new Humans();var Merry = new Humans();

Tom.ability = false;
console.log(Tom.foot);//结果:2console.log(Tom.ability);//结果:falseconsole.log(Merry.foot);//结果:2console.log(Merry.ability);//结果:true
Copy after login

It can be seen from the above that the value of Tom's ability attribute has changed, but it does not affect the value of Merry's ability attribute. This is exactly the result we want, and it is also object-oriented. The advantage is that objects instantiated from the same class do not interfere with each other; OK, what about replacing ability with object objects? The code is as follows:

function Humans() {    this.foot = 2;
}
Humans.prototype.ability = {
    run : '100米/10秒',
    jump : '3米'};var Tom = new Humans();var Merry = new Humans();

Tom.ability = {
    run : '50米/10秒',
    jump : '2米'};console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'100米/10秒'console.log(Merry.ability.jump); //结果:'3米'
Copy after login
Copy after login

The above code is in the prototype chain Object is used on the above code, but it can be seen from the above code that the change of Tom's ability attribute will not affect Merry's ability attribute at all, so you may think that there is nothing wrong with this approach. Why can't you use objects on the prototype chain? ?The following code will look very different, and can fully express the danger of using objects on the prototype chain:

function Humans() {    this.foot = 2;
}
Humans.prototype.ability = {
    run : '100米/10秒',
    jump : '3米'};var Tom = new Humans();var Merry = new Humans();

Tom.ability.run = '50米/10秒';
Tom.ability.jump = '2米';console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'50米/10秒'console.log(Merry.ability.jump); //结果:'2米'
Copy after login
Copy after login

Yes, from the output of the above code, we can see that Tom’s ability attribute The change affects Merry's ability attribute, so we can understand that using objects on the prototype chain is very dangerous. It can easily break the mutual independence between instantiated objects. This is why objects cannot be used on the prototype chain. ?Yes, but what I want to say is not just that, but the principle. After reading the deep principles of the JS prototype chain later, I believe you will fully understand it.

Before explaining the deep principles of the JS prototype chain in the second part below, let’s first clarify a concept: The properties or methods on the prototype chain are all shared by instantiated objects. Therefore, the above Tom.ability.run='50 meters/10 seconds' changes the ability of the prototype connection, which affects another object Merry. In this case, you may ask Tom.ability = {......} Didn't it also change the ability on the prototype chain? Why was Merry not affected? The answer is that Tom.ability = {...} did not change the ability attribute on the prototype chain, but added a self-owned attribute ability for Tom. When accessing Tom.ability, you no longer need to access the ability on the prototype chain, but access its own attribute ability. This is the principle of proximity; OK, if you still have questions, you can use paper and pen to write down your questions and continue. You will understand better after watching.

2. The deep principle of JS prototype chain:

First, we must introduce a noun __proto__, what is __proto__? In my understanding, __proto__ is the real prototype chain, and prototype is just a shell. If you are using the chrome browser, then you can try to use console.log(Tom.__proto__.ability.run). You find that this way of writing is completely feasible, and in fact, when ability exists only on the prototype chain Attributes, Tom.ability actually points to Tom.__proto__.ability; of course, if you try it in IE browser, you will definitely get an error. In fact, IE browser prohibits access to __proto__ access, while chrome allows it. Of course, in actual development, I do not recommend using the __proto__ attribute directly, but it often plays an important role when we debug the code. Some people may ask what the relationship is between Tom.__proto__ and Humans.prototype. In order to clarify the relationship between the two, three rules are listed below:

 1 , the object has the __proto__ attribute, but does not have the prototype; for example: there is Tom.__proto__, but there is no Tom.prototype.

 2. The class does not have the __proto__ attribute, but has prototype; for example: there is no Humans.__proto__, but there is Humans.prototype (This must be corrected, and I am very grateful to 'Brother Chuanchuan' for pointing out this error. It is true that I did not think clearly when I wrote this point. In fact, Humans is also an instance object of Function, so Humans. __proto__===Function.prototype is absolutely true. What is a little special is that Function.prototype points to an Empty (empty) function at this time, which is worthy of consideration).

  3、由同一个类实例化(new)得到的对象的__proto__是引用该类的prototype的(也就是我们说的引用传递);例如Tom和Merry的__proto__都引用自Humans的prototype

  OK,上面说过Tom.ability={……}其实并没有改变原型链上的ability属性,或者说并没有改变Tom.__proto__.ability,而是为Tom添加了一个自有的ability属性,为了说明这一点,我们再次回到以上的第三个代码块,其代码如下:

function Humans() {    this.foot = 2;
}
Humans.prototype.ability = {
    run : '100米/10秒',
    jump : '3米'};var Tom = new Humans();var Merry = new Humans();

Tom.ability = {
    run : '50米/10秒',
    jump : '2米'};console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'100米/10秒'console.log(Merry.ability.jump); //结果:'3米'
Copy after login
Copy after login

当为Tom.ability赋予新的值后,再次访问Tom.ability时就不再指向Tom.__proto__.ability了,因为这时其实是为Tom添加了自有属性ability,可以就近取值了,你可以尝试用Chrome浏览器分别console.log(Tom.ability.run)和console.log(Tom.__proto__.ability.run),你会发现确实存在两个不同的值,再看完下面的图后,相信你会完全明白:
Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain于是可以有这样一个结论:当访问一个对象的属性或方法的时候,如果对象本身有这样一个属性或方法就会取其自身的属性或方法,否则会尝试到原型链(__proto__)上寻找同名的属性或方法。明白了这一点后,要解释以上第四个代码块的原理也非常容易了,其代码如下:

function Humans() {    this.foot = 2;
}
Humans.prototype.ability = {
    run : '100米/10秒',
    jump : '3米'};var Tom = new Humans();var Merry = new Humans();

Tom.ability.run = '50米/10秒';
Tom.ability.jump = '2米';console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'50米/10秒'console.log(Merry.ability.jump); //结果:'2米'
Copy after login
Copy after login

当Tom.ability.run=’50米/10秒’的时候,JS引擎会认为Tom.ability是存在的,因为有Tom.ability才会有Tom.ability.run,所以引擎开始寻找ability属性,首先是会从Tom的自有属性里寻找,在自有属性里并没有找到,于是到原型链里找,结果找到了,于是Tom.ability就指向了Tom.__proto__.ability了,修改Tom.ability.run的时候实际上就是修改了原型链上的ability了,因而影响到了所有由Humans实例化得到的对象,如下图:
Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain

希望上面所讲的内容足够清楚明白,下面通过类的继承对原型链作更进一步的深入:
先来看一个类的继承的例子,代码如下:

function Person() {
    this.hand = 2;    this.foot = 2;
}
Person.prototype.say = function () {
    console.log('hello');
}function Man() {
    Person.apply(this, arguments);//对象冒充
    this.head = 1;
}
Man.prototype = new Person();//原型链Man.prototype.run = function () {
    console.log('I am running');
};
Man.prototype.say = function () {
    console.log('good byte');
}var man1 = new Man();
Copy after login

以上代码是使用对象冒充和原型链相结合的混合方法实现类的继承,也是目前JS主流的实现类的继承的方法,如果对这种继承方法缺乏了解,可以看看这里。

  接下来看看以上实现继承后的原型链,可以运用prototype__proto__来解释其中的原理:

  1、从man1 = new Man(),可以知道man1的__proto__是指向Man.prototype的,于是有:

  公式一:man1.__proto__ === Man.prototype 为true

  2、从上面的代码原型链继承里面看到这一句代码 Man.prototype = new Person(),作一个转换,变成:Man.prototype = a,a = new Perosn();一个等式变成了两个等式,于是由a = new Perosn()可以推导出a.__proto__ = Person.prototype,结合Man.prototype = a,于是可以得到:

  公式二:Man.prototype.__proto__ === Person.prototype 为true

  由公式一和公式二我们就得出了以下结论:

  公式三:man1.__proto__.__proto__ === Person.prototype 为true

  公式三就是上述代码的原型链,有兴趣的话,可以尝试去推导多重继承的原型链,继承得越多,你会得到一个越长的原型链,而这就是原型链的深层原理;从公式三可以得出一个结论:当你访问一个对象的属性或方法时,会首先在自有属性寻找(man1),如果没有则到原型链找,如果在链上的第一环(第一个__proto__)没找到,则到下一环找(下一个__proto__),直到找到为止,如果到了原型链的尽头仍没找到则返回undefined(这里必须补充一点:同时非常感谢深蓝色梦想提出的疑问:尽头不是到了Object吗?是的,原型链的尽头就是Object,如果想问为什么,不妨做一个小小的实验:如果指定Object.prototype.saySorry = ‘I am sorry’,那么你会惊喜地发现console.log(man1.saySorry)是会弹出结果‘I am sorry’的)。

  以上就是原型链的深层原理,说难其实也算容易,如果细心研究,会发现原型链上有很多惊喜。

相关文章:

js中的作用域链和原型链以及原型继承

js的原型及原型链详解

相关视频:

JavaScript basic syntax and basic statement video tutorial

The above is the detailed content of Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template