javascript constructor with arguments

There was an interesting question on stackoverflow recently. Nobody had right answer. Now after few days i got it! It is really a peace of JS art.
The question was if it is possible to call constructor like this:

someClass(arg1,arg2,...,argN){
.... //implementation
}

having just an Array of arguments [arg1,arg2,...,argN]. First thought was just to use apply. Next was: how can you use apply on a constructor? But it seems you really can:)

var args=[arg1,arg2,...,argN];
var inst={};// this will be instance of our class
someClass.apply(inst,args);// magic here

You see from this point of view javascript constructor is just a method(function) applied to object cloned from its prototype.

This entry was posted in post and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>