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
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>