Home >Web Front-end >JS Tutorial >Detailed explanation of Javascript constructor_basic knowledge
1. What is a constructor
In some object-oriented languages, such as Java, C, and PHP, constructors are very common. In Javascript, the constructor is first an ordinary function, which can be called using the new operator and generates an object of a special type.
In the above example, benjamin is a Benjamin object, so how is it instantiated?
As we can see, the "Benjamin" constructor simply receives the parameters passed in and assigns them to the this object. This is because when the constructor is called by the new operator, the this object of the constructor is assigned the object returned by the new operation.
This means that the above code is equivalent to:
2. Why use constructor
There are several reasons why constructors are used:
1. Using constructors means that all these objects can be created using the same basic structure
2. Using a constructor means that the "benjamin" object is explicitly marked as an instance of the "Benjamin" function
3. Using constructors means that we can define public methods on the prototype for sharing by multiple instances
3. Precautions
1.new keyword
Don't forget to use the new keyword when instantiating the constructor. Whether to use the new keyword has a great impact on the this object. Without the new keyword, the this object will point to the global object (window in browser and global in node). Therefore, when defining a constructor, it is recommended that the first letter of the function name be capitalized.
2. If the called function does not have an explicit return expression, it will implicitly return the this object - that is, the newly created object. Otherwise, it will affect the returned result, but only if it returns an object
What we need to pay attention to is:
a) new Bar() returns the newly created object, not the literal value of the number 2. Therefore new Bar().constructor === Bar, but if a numeric object is returned, the result is different;
b) The new Test() obtained here is the object returned by the function, not the newly created object through the new keyword, as shown below:
The above is a summary of the constructor function. I hope it will be helpful to beginners. If there is anything inappropriate in the article, I hope to criticize and correct it.