Can someone clarify the difference between a constructor function and a factory function in Javascript.
When to use one instead of the other?
function User(name) {
this.name = name;
this.isAdmin = false;
}
let user = new User("Jack");
new
creates an object prototyped on User.prototype
and calls User
with the created object as its this
value.
new
treats an argument expression for its operand as optional:
let user = new User;
would cause new
to call User
with no arguments.
new
returns the object it created, unless the constructor returns an object value, which is returned instead. This is an edge case which for the most part can be ignored.
Objects created by constructor functions inherit properties from the constructor's prototype
property, and return true using the instanceOf
operator on the constructor function.
The above behaviors can fail if you dynamically change the value of the constructor's prototype
property after having already used the constructor. Doing so is rare, and it can't be changed if the constructor were created using the class
keyword.
Constructor functions can be extended using the extends
keyword.
Constructor functions can't return null
as an error value. Since it's not an object data type, it is ignored by new
.
function User(name, age) {
return {
name,
age,
}
};
let user = User("Tom", 23);
Here the factory function is called without new
. The function is entirely responsible for the direct or indirect use if its arguments and the type of object it returns. In this example it returns a simple [Object object] with some properties set from arguments.
Easily hides the implementation complexities of object creation from the caller. This is particularly useful for native code functions in a browser.
The factory function need not always return objects of the same type, and could even return null
as an error indicator.
In simple cases, factory functions can be simple in structure and meaning.
Objects returned do not generally inherit from the factory function's prototype
property, and return false
from instanceOf factoryFunction
.
The factory function can't be safely extended using the extends
keyword because extended objects would inherit from the factory functions prototype
property instead of from the prototype
property of the constructor used by the factory function.