You are right, this is basically what new
is doing: Create a new object that inherits from Func.prototype
and call Func
with this
referring to this new object.
There is a slight difference to your implementation though: If the constructor (Func
) does not return an object, this
is implicitly returned. If it returns an object (any object) than it will become the return value of the constructor call.
So a more accurate replication would be:
var _new = function(fn) {
var obj = Object.create(fn.prototype);
var result = fn.apply(obj);
return result != null && typeof result === 'object' ? result : obj;
};
That's it. You can see it as syntactic sugar if you want to, just like the conditional operator.
Some pointers to the reference: When new
is used, the internal [[Construct]]
function of the constructor is called. What exactly happens is described in section 13.2.2 of the specification and it pretty much does the same as the function you (and I) wrote.
The point I'm not completely sure about is that the object's internal [[Extensible]]
property is set to true
. I would assume that every object you create via Object.create
is extensible by default (if it's prototype is extensible).