Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create new javascript object from variable

Tags:

javascript

oop

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?

like image 864
yee379 Avatar asked Apr 30 '11 01:04

yee379


People also ask

How do you create a new object in JavaScript?

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() .

Can you make objects in JavaScript?

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.


1 Answers

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')
like image 123
meder omuraliev Avatar answered Sep 22 '22 21:09

meder omuraliev