开发者

create new javascript object from variable

i would like to create a new object in javascript (using simple inheritance) s开发者_JAVA技巧uch that the class of the object is defined from a variable:

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

any ideas?


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')


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');


To improve on the answer above by meder:

To invoke using a function:

You would simply replace 'this' with the scope containing the class you are referring to, for example if the class is written in the global scope like below:

function Person(name){alert(name)};
var name = 'Person';

function classMaker(){
  var inst = new window[name]('john');
}

classMaker();


To put it more plainly, you can use new on a variable that references a class:

class Person{}
const class_type = Person;
const instance = new class_type();
console.log("works?", instance instanceof Person); // true


I had a similar problem in Node.js, when I had to dynamically create different handler objects depending on the data. First I gathered all available handlers, which were implemented as separate modules, in an object. In a simple case this could be hardcoded like this.

var handlers = {
  handlerX : require('HandlerX'),
  handlerY : require('HandlerY')
};

Then, whenever I had to instantiate a handler, I did it like this:

var handlername = getHandlerName()
var handler = new handlers[handlername]();

Of course this only works if you know, or can programmatically determine the list of all objects you will need to create.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜