Search code examples
javascriptapplyinvocation

Crockford "new" method


hope someone can help me to break down a snippet of code from Crockford's JS Good Parts:

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 part that I don´t understand is when he uses the apply invocation pattern to create an object:

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

How executing the this function will create the new object?

If the function will be:

var f = function (name) {
   this.name = "name";
};

How calling:

var myF = f.new("my name");

creates the object?


Solution

  • First, note Function.method isn't a built-in JS method. It's something Crockford made up:

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

    Therefore, that Function.method method call basically does this:

    Function.prototype.new = function() {
      var that = Object.create(this.prototype);
      var other = this.apply(that, arguments);
      return (typeof other === 'object' && other) || that;
    });
    

    Then when you use it like

    f.new("my name");
    

    it does this:

    1. First, it creates an object which inherits from f.prototype (instance).
    2. Then, it calls f passing that instance as the this value.
      • In this case, this will set the name property to the instance.
      • This step doesn't create any new instance, the instance was created at step 1.
    3. If the call to f returned some object, that object is returned.
      Otherwise, the instance created at step 1 is returned.