In addition to creating objects, the constructor (constructor) also does another useful thing--automatically sets the prototype object (prototype objects) for the new object that was created. The prototype object is stored in the Constructorfunction.prototype property.
For example, if we rewrite the previous example, using constructors to create objects "B" and "C", then object "A" plays the role of "Foo.prototype":
The constructor function Foo (y) { ///constructor will create the object in a specific pattern: the object being created will have the "Y" property this.y = y;}//"Foo.prototype" holds the prototype reference for the new object// So we can use it to define inheritance and shared properties or methods//So, as in the example above, we have the following code://Inheritance Property "x" foo.prototype.x = 10; Inheritance method "Calculate" Foo.prototype.calculate = function (z) { return this.x + This.y + z;};//use Foo mode to create "B" and "C" Var b = new Foo, var c = new Foo (30); Method of invoking Inheritance B.calculate (30); 60c.calculate (40); 80//Let's see if the expected properties are used Console.log ( b.__proto__ = = = Foo.prototype,//true c.__proto__ = = = Foo.prototype,//Tru E //"Foo.prototype" automatically creates a special attribute "constructor"// the constructor of a to itself// instance "B" and "C" can be found by authorization and used to detect its own constructor B.constructor = = = Foo,//true c.constructor = = = Foo,//true Foo.prototype.constructor = = = Foo//True b.ca Lculate = = = B.__proto__.calculate,//true b.__proto__.calculate = = = Foo.prototype.calculate//TRUE);
The above code can be expressed as the following relationship:
The relationship between constructors and objects
As you can see from the above diagram, each object has a prototype. The constructor Foo also has its own __proto__, which is Function.prototype, and Function.prototype's __proto__ points to Object.prototype. Again, Foo.prototype is just an explicit attribute, that is, the __proto__ property of B and C.
The complete and detailed explanation of this problem has two parts:
- Object-oriented programming. General Theory (OOP. The general theory), describes different object-oriented paradigms and styles (OOP Paradigms and Stylistics), and comparisons with ECMAScript.
- Object-oriented programming. ECMAScript implementation (OOP. ECMAScript implementation), which specifically describes object-oriented programming in ECMAScript.
Now that we've learned the basic object principle, let's take a look at the program execution environment in ECMAScript [runtime programs execution]. This is what is commonly referred to as the "execution context stack" [execution context Stack]. Each element can be abstractly understood as an object. You may have found out, yes, in the ECMAScript, almost everywhere you can see the figure of object.
JavaScript Quest: Constructor Constructor