This article introduces the prototype and prototype chain in javascript. For more information, see
Prototype
As we all know, JavaScript does not contain the traditional class inheritance model, but uses the prototype model. Code implementation is like this.
function Student(name){ this.name = name;} var Kimy = new Student("Kimy"); Student.prototype.say = function(){ console.log(this.name + "say");}Kimy.say();//Kimysay
Kimy itself does not have the say method. If he cannot find this method in his object, he will go back to his prototype to find it, that is, the Student. prototype object. Here we use a constructor Student.
Constructor, _ proto _, and prototype chain
In addition to the IE browser, all other browsers deploy a non-standard _ proto _ attribute (two underscores (_) on the instance of the Object, 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); // 80 console. 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.
I want to understand such a piece of code here.
Object instanceof Function//trueFunction instanceof Object//true
What did new do?
There is also a small problem here. In JavaScript, there seems to be no big difference in the form of common functions and constructor (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 has done three things.
var Kimy = {}; Kimy.__proto__ = Student.prototype;Student.call(Kimy);
1. defines an empty object
2. Set its prototype
3. initialize the object
In this way, we can understand why Kimy. _ proto _ points to Student. prototype (the same reference). It turns out that new plays a key role!
The above is all the content of this article. I hope you will like it.