Lasse said:
3. Create the Point object without using the Point constructor:
function Point() {
var self = this;
if (!(self instanceof Point)) {
self = new UninitializedPoint;
}
// initialize self
self.x = arguments[0];
self.y = arguments[1];
}
function UninitializedPoint() {}
UninitializedPoint.prototype = Point.prototype;
You have to explicitly return the `self' from the constructor,
especially when the `Point' it has called as a function, instead of
`new Point`.
Your approach does not solve the problem the variable length of
arguments, but it is really elegant and allows for implement it
without full emulation of internal [[Construct]].
Function.prototype.construct = (function () {
function F(constructor, args) {
constructor.apply(this, args);
}
return function (args) {
F.prototype = this.prototype;
return new F(this, args);
};
})();
//Soshnikov ES5 example
function Point(x, y) {
this.x = x;
this.y = y;
}
var foo = Point.construct([2, 3]);
print(foo.x);
print(foo.y);
print(foo.constructor);
This approach increase the call stack size, but I think it is the most
straightforward and compatibility way to achieve variable length of
passed arguments to certain constructor.
Regards.