从变量创建新的JavaScript对象 [英] create new javascript object from variable

查看:131
本文介绍了从变量创建新的JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在javascript中创建一个新对象(使用简单继承),以便从变量定义对象的类:

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

有什么想法吗?

推荐答案

您可以执行类似的操作

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

键只是引用拥有构造函数的对象.这在全局范围内可以正常工作,但是如果要将代码转储到函数内部,则可能必须更改引用,因为this可能无法正常工作.

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.

编辑:要传递参数:

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

这篇关于从变量创建新的JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆