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.
take control over class constructor
Javascript doesn’t give us simple way to control object constructing. We have new operator, but we cannot control it. Unless we do some magic.
Lets assume we have an observer instance, few classes and we want every instance of this classes to be ‘observed’.
var observer=[]// simplest ever function foo(){ this.foo="foo"; .... } function bar(){ this.bar="bar"; .... } function observe(child){ //MAGIC childName=child.name||child.toString().match(/function\s*([^\(])\s*\(/)[1]; newConst=function(){ ret={}; child.apply(ret, arguments); observer.push(ret); return ret; }; newConst.name=childName; window[childName]=newConst; } observe(foo); observe(bar); var t1=new foo(); var t2=new bar(); observer // t1,t2