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?
Creating a JavaScript Object Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .
JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With