2014-01-19

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:
  1. JavaScript inheritance by example
  2. In defense of JavaScript’s constructors [Why I recommend constructors, even though they are far from perfect]
  3. Exemplar patterns in JavaScript [alternatives to constructors as factories for objects]
  4. JavaScript terminology: the two prototypes

No comments: