Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i would like to create a new object in javascript (using simple inheritance) such that the class of the object is defined from a variable:

var class = 'Person';
var inst = new class

any ideas?

share|improve this question

4 Answers

up vote 12 down vote accepted

You can do something like

function Person(){};
var name = 'Person';
var inst = new this[name]

The key is just referencing the object that owns the function that's the constructor. This works fine in global scope but if you're dumping the code inside of a function, you might have to change the reference because this probably wont work.

EDIT: To pass parameters:

function Person(name){alert(name)};
var name = 'Person';
var inst = new this[name]('john')
share|improve this answer
+1 very nice meder – alex Apr 30 '11 at 1:46
thanks! how do i pass parameters? – yee379 Apr 30 '11 at 1:48
You can also use apply to pass parameters, which is useful if you don't know them in advance, a.g. this[name].apply(null, args) where args is an array of parameters/arguments. Seems to be the case more often than not when calling functions dynamically. – Jamie Treworgy Apr 30 '11 at 13:19
This solution saved me having to use eval(). Thank you! – Jimmy Breck-McKye Jan 6 at 22:11

This talk was really helpful when I got into different inheritance patterns in javascript. Example code is included in the second link (the video introduces it).

http://alexsexton.com/?p=94

http://alexsexton.com/inheritance/demo/

http://alexsexton.com/?p=51

HTH

share|improve this answer

Try

function Person(name, age, gender) { //and any other params you need
return {
name: name,
age: age,
gender: gender
}
});
var p = new Person("Billy Bob", "Too Old", "Male???");
share|improve this answer

Here's how I do it. Similar to meder's answer.

var className = 'Person'
// here's the trick: get a reference to the class object itself
// (I've assumed the class is defined in global scope)
var myclass = window[className];
// now you have a reference to the object, the new keyword will work:
var inst = new myclass('params','if','you','need','them');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.