For newcomers, JavaScript prototype is a very troublesome thing. First, prototype is easy to be confused with __proto__, and second, the various directions between them are really complicated. In fact, there are already many articles on the market trying to make it clear. There is a so-called classic picture with various lines drawn on it, connecting this one and that one. To be honest, I feel very dizzy myself, let alone fully understand it. So I also want to try it myself to see if I can separate out the important knowledge points in the prototype and explain it clearly in the simplest chart form.
We know that the prototype is an object through which other objects can implement attribute inheritance. But in addition to prototype, there is another __proto__ used for? How can people distinguish it if they look so similar? Who are they pointing to? How can you remember the chaos? What the hell is the prototype chain? I believe that many beginners who even have some experience may not be able to explain it completely. The following is three simple pictures and some example codes to understand.
1. The difference between prototype and __proto__
var a = {};console.log(a.prototype); //undefinedconsole.log(a.__proto__); //Object {}var b = function(){}console.log(b.prototype); //b {}console.log(b.__proto__); //function() {} /*1. Literal method*/var a = {};console.log(a.__proto__); //Object {}console.log(a.__proto__ === a.constructor.prototype); //true/*2. Constructor method*/var A = function(){};var a = new A();console.log(a.__proto__); //A {}console.log(a.__proto__ === a.constructor.prototype); //true/*3. Object.create() method*/var a1 = {a:1}var a2 = Object.create(a1);console.log(a2.__proto__); //Object {a: 1}console.log(a.__proto__ === a.constructor.prototype); //false (This is the exception in Figure 1) var A = function(){};var a = new A();console.log(a.__proto__); //A {} (i.e. the prototype object of constructor function A) console.log(a.__proto__.__proto__); //Object {} (i.e. the prototype object of constructor function Object) console.log(a.__proto__.__proto__.__proto__); //nullThe above is all about this article. This article uses three pictures to explain the prototype objects and prototype chains of JavaScript. I hope it will be helpful to everyone when learning JavaScript.