Javascript prototype and prototype chain
As we all know, JavaScript does not contain the traditional class inheritance model, but uses the prototype model. The code implementation is probably like copying the code function Student (name) {this. name = name;} var Kimy = new Student ("Kimy"); Student. prototype. say = function () {console. log (this. name + "say");} Kimy. say (); // Kimysay there is no way to copy the code Kimy itself. If he cannot find this method in his object, he will go back to his prototype to find it, that is, Student. search for prototype objects. Here we use a constructor: Student constructor, _ proto _, and prototype chain. Except for IE browser, other browsers are on the instance of the Object, A non-standard _ proto _ attribute is deployed, pointing to the prototype object of the object, that is, the prototype attribute of the constructor. Stealing a piece of code and a picture
// Constructor function Foo (y) {this. y = y;} Foo. prototype. x = 10; // The Inheritance Method "calculate" Foo. prototype. calculate = function (z) {return this. x + this. y + z ;}; // use the foo mode to create "B" and "c" var B = new Foo (20); var c = new Foo (30 ); // call the inherited method B. calculate (30); // 60c. calculate (40); // 80console. log (B. _ proto _ = Foo. prototype, // true c. _ proto _ = Foo. prototype, // true B. constructor = Foo, // true c. constructor = Foo, // true Foo. prototype. constructor = Foo // true B. calculate = B. _ proto __. calculate, // true B. _ proto __. calculate = Foo. prototype. calculate // true );
We can see that each object contains a _ proto _ attribute, and B's _ proto _ points to the prototype attribute of Constructing B's constructor Foo; and Foo. prototype is also an Object, and it also has a _ proto _ pointing to the prototype of the Object construction method. The _ proto _ of Object. prototype is pointed to null, which forms a prototype chain. Here we also need to understand the code Object instanceof Function // trueFunction instanceof Object // true new. There is another small problem here, in js, there seems to be no big difference between common functions and constructor forms (uppercase is not a must, but usually uppercase is the first letter of the constructor ). What did the new Keyword do. For example, var Kimy = new Student (); new does three things: var Kimy ={}; Kimy. _ proto _ = Student. prototype; Student. call (Kimy); 1. Define an empty object 2. set its prototype 3. initialize the object so that you can understand why Kimy. _ proto _ points to Student. prototype (same reference). It turns out that new plays a key role!