DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Function.prototype.newInstance

09.19.2005
| 8362 views |
  • submit to reddit
        
Function.prototype.New = 
Function.prototype.newInstance = function(){
	for(var i=0,arg=[];i<arguments.length;i++) arg.push("arguments["+i+"]");
	eval("var ins = new this("+arg.join(",")+")");
	return ins;
}

// example

// way to get [1,2,3]
new Array(1,2,3)
Array.New(1,2,3)
Array.newInstance(1,2,3)

// getClass and newInstance
var foo = [];
foo.constructor.New("12345") // [12345]

var foo = "";
foo.constructor.New("12345") // "12345"