Subj : Re: Using 'apply' to construct an object To : Alexis Nikichine From : Brendan Eich Date : Wed Aug 31 2005 10:31 am Alexis Nikichine wrote: > 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: Sure, but these are both workarounds. The way Franck and Narcissus do it is limited to a certain number of arguments, but does a true constructor call. The way you do it (cited below) wastes an object, but does not have the arguments limit. Neither is ideal. /be > 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 .