Subj : Re: Using 'apply' to construct an object To : netscape.public.mozilla.jseng From : Alexis Nikichine Date : Wed Aug 31 2005 02:49 pm Brendan Eich wrote: > franck wrote: > >> In fact, I want to create an object ( new myClass... ) with a variable >> argument list ( ...apply( xxx, myListOfArguments ) ) >> >> An alternative way to achieve this is : >> >> new myClass( args[0], args[1], args[2], args[3], args[4], ... >> args[n] ); >> >> But the constructor of the object I am trying to create failed if I >> provide more than the expected number of arguments. > > > You are quite right that it's not possible to combine new with apply, > unfortunately. We hit this working on Narcissus > (http://lxr.mozilla.org/mozilla/source/js/narcissus/jsexec.js -- look > for __construct__). > > This is something to work around for now, as you propose and as we did > for Narcissus. We'll fix it for Edition 4 / JS2. But let me point out that it is possible to work around it while staying in the current language: var constructWithArgs = (function() { function Dummy(){ ; }// Scope-contained, "private", // dummy constructor. No other code // needs access to this constructor. return (function(fun, args) { Dummy.prototype = fun.prototype; var tmp = new Dummy; // Internal [[Prototype]] of new // object is set to fun.prototype // but no other properties are // created/changed. fun.apply(tmp, args); // Use constructor to create/apply // new properties to the Dummy instance, // creating an object indistinguishable // form one created with - fun -. return tmp; // Return the new object } ) }) I won't claim credits for this, but leave them to Richard Cornford in http://groups.google.fr/group/comp.lang.javascript/msg/6e06b7884b3db6ad Or was some flaw overlooked in this code ? Cheers, Alexis -- Some domain is free .