The new operator implemented in JavaScript
Code snippet – this is roughly how you would implement the
new operator in JavaScript:
function newOperator(Constr, args) {
var thisValue = Object.create(Constr.prototype); // (1)
var result = Constr.apply(thisValue, args);
if (typeof result === 'object' && result !== null) {
return result; // (2)
}
return thisValue;
}
Two things are noteworthy:
- Line 1: The prototype of a new instance of a constructor Constr is Constr.prototype [4]
- Line 2: The implementor of a constructor can override that the new operators returns this, by returning an object. This is useful when a constructor should return an instance of a sub-constructor. The blog post [3] gives an example.
Further reading:
- JavaScript inheritance by example
- In defense of JavaScript’s constructors [Why I recommend constructors, even though they are far from perfect]
- Exemplar patterns in JavaScript [alternatives to constructors as factories for objects]
- JavaScript terminology: the two prototypes