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
Fis called with the arguments passed andthisset 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
328

被折叠的 条评论
为什么被折叠?



