The new
operator takes a function F
and arguments: new F(arguments...)
. It does three easy steps:
- Create the instance of the class. It is an empty object with its
__proto__
property set toF.prototype
. - Initialize the instance. The function
F
is called with the arguments passed andthis
set to be the instance. - Return the instance
Now that we understand what the new
operator does, we can implement it in Javascript.
function New (f) {
/*1*/ var n = { '__proto__': f.prototype };
return function () {
/*2*/ f.apply(n, arguments);
/*3*/ return n;
};
}
And just a small test to see that it works.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
print: function () { console.log(this.x, this.y); }
};
var p1 = new Point(10, 20);
p1.print(); // 10 20
console.log(p1 instanceof Point); // true
var p2 = New (Point)(10, 20);
p2.print(); // 10 20
console.log(p2 instanceof Point); // true