Alexis Nikichine <alexis.nikichine@somedomain.fr> writes:
[color=blue]
> The closest I could get was by using an helper function to construct
> my object in two passes.
>
> function constructWithArgs( fun, args )
> {
> var tmp = new fun; // first, make an object of 'fun' constructor
> fun.apply(tmp, args); // second, 'fills' it with arguments
> return tmp;
> }
>
> But this requires that "new fun" won't fail, and some other
> constraints on fun.[/color]
It should be possible to create an object that is indistinguishable
from one created using the constructor, but actually using another
constructor that you know will not fail. It will still be two-phase,
but the first phase is under your control :).
---
function newApply(constructor, argsArray) {
function dummyConstructor (){};
dummyConstructor.prototype = constructor.prototype;
var object = new dummyConstructor();
var sndObject = constructor.apply(object, argsArray);
return (typeof sndObject == "object" ? sndObject : object);
}
---
(It really implements the behavior of [[Construct]] on function
objects as specified in ECMA 262 section 13.2.2, except using apply to
call the function with an array of arguments).
You can the use it as:
---
function Const(x,y) {
this.x = x;
this.y = y;
}
Const.prototype.z = 42;
var o = newApply(Const,[2,4]); // equivalent to: new Const(2,4)
alert([o instanceof Const, o.x, o.y, o.z]); // true,2,4,42
---
/L
--
Lasse Reichstein Nielsen -
lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'