Home > Article > Web Front-end > Javascript study notes - functions (5): Constructor_Basic knowledge
Constructors in Javascript are also different compared to other languages. Any function called with the new keyword can be used as a constructor.
Within the constructor body, this points to the newly created object. If there is no return expression displayed in the constructor body, then we will return this by default, which is the newly created object.
The above code calls Foo as a constructor and points the prototype (__proto__) of the new object to Foo.prototype.
If we define the return expression within the constructor, the constructor will return the entire expression, but this return expression must be an object.
If new is omitted, the function will not be able to return a new object.
The above example may also work in some scenarios, but due to the working mechanism of this in Javascript, this will point to the global object.
Factory Mode
In order to be able to do without the keyword new, the constructor would have to explicitly return a value.
In the above example, the effect of calling the function Bar without using new is the same. A newly created object containing the method method will be returned. This is actually a closure.
One thing to note here is that new Bar() will not return Bar.prototype, but the prototype object of the function method within the return expression.
In the above example, there is no functional difference between using new or not.
Create new objects through factory pattern
We are often reminded not to use new because forgetting its use will lead to errors.
To create an object, we prefer to use the factory pattern and construct a new object inside the factory pattern.
var private = 2;
Obj.someMethod = function(value) {
This.value = value;
}
obj.getPrivate = function() {
return private;
}
Return obj;
}
Although the above code is less error-prone than using new and will be more convenient when using private variables, it also has some disadvantages:
Because prototype objects cannot be shared, more memory is required.
In order to implement inheritance, the factory pattern needs to copy all methods of another object or use it as the prototype of a new object.
Abandoning the prototype chain just to avoid using new seems to go against the spirit of the Javascript language.
Summary
Although using new may be more error-prone, this is not a reason to give up using the prototype chain. As for the final approach, it depends on the needs of the application. The best way is to pick a style and stick to it.
To put it simply, the constructor initializes an instance object, and the prototype attribute of the object inherits an instance object.