What does the new keyword do under the hood?

Quoting Douglas Crockford from the Good Parts book (page 47), to answer the title of this question:

If the new operator were a method instead of an operator, it could be implemented like this:

Function.method('new', function () {

   // Create a new object that inherits from the 
   // constructor's prototype.

   var that = Object.create(this.prototype);

   // Invoke the constructor, binding -this- to
   // the new object.

   var other = this.apply(that, arguments);

   // If its return value isn't an object,
   // substitute the new object.

   return (typeof other === 'object' && other) || that;
});

The Function.method method is implemented as follows. This adds an instance method to a class (Source):

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};

Further reading:

Leave a Comment