Recently, I needed the ability to dynamically instantiate Javascript classes with custom construction arguments. A quick search on the web didn't yield any good answers. Thus, this is my attempt to address the knowledge gap.
Here's the function:
/*
* Dynamically instantiate a class. Additional arguments are
* passed to the class constructor
*
* @param {Function} clazz
* @returns {Object} The instantiated class instance.
*/
function instantiate( clazz ) {
var tempClass,
inst,
args;
tempClass = function(){};
tempClass.prototype = clazz.prototype;
inst = new tempClass();
args = Array.prototype.slice.call( arguments );
args.shift();
clazz.apply( inst, args );
return( inst );
}
In the following example, clicking the 'Run' button will
Instantiate a Test class instance
Run Test::run() which will output the construction argument string to the output console.
Chris Khoo cut his teeth on programming writing BASIC programs on a ZX Spectrum back in 1985. Since then, he's graduated to programming on the web and on nearly all the game consoles released since the mid-90's. Chris remains an active member of the software industry and is currently operating as indie developer and founder of Wappworks Studio.