In addition to creating objects, the constructor also does another useful thing - automatically sets the prototype object for the new object created. The prototype object is stored in the ConstructorFunction.prototype property.
For example, if we rewrite the previous example and use the constructor to create objects "b" and "c", then object "a" plays the role of "Foo.prototype":
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
The above code can be expressed as the following relationship:
The relationship between constructor and object
As can be seen from the above diagram, each object has a prototype. The constructor Foo also has its own __proto__, which is Function.prototype, and the __proto__ of Function.prototype points to Object.prototype. Let me reiterate. , Foo.prototype is just an explicit attribute, that is, the __proto__ attribute of b and c.
A complete and detailed explanation of this question has two parts:
Object-oriented programming. The general theory (OOP. The general theory) describes different object-oriented paradigms and stylistics (OOP paradigms and stylistics), as well as comparison with ECMAScript.
Object-oriented programming. ECMAScript implementation (OOP. ECMAScript implementation), specifically talks about object-oriented programming in ECMAScript.
Now that we have understood the basic object principles, let's take a look at the program execution environment [runtime program execution] in ECMAScript. This is commonly called the "execution context stack" [execution context stack]. Each element can be understood abstractly as an object. You may have discovered that, yes, in ECMAScript, you can see objects almost everywhere.
The following is a detailed explanation of JavaScript constructor properties
The constructor attribute of an object is used to return the function that created the object, which is what we often call the constructor.
In JavaScript, every object with a prototype automatically gets the constructor attribute. Except for some special objects such as arguments, Enumerator, Error, Global, Math, RegExp, Regular Expression, etc., all other JavaScript built-in objects have the constructor attribute. For example: Array, Boolean, Date, Function, Number, Object, String, etc. All major browsers support this attribute.
Grammar
object.constructor
Return value
The constructor property of an object returns a reference to the function that created the object.
Examples & Instructions
[native code] in the following code indicates that this is the underlying internal code implementation of JavaScript, and code details cannot be displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|