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?
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:
f.prototype
(instance).f
passing that instance as the this
value.
name
property to the instance.f
returned some object, that object is returned.