我想在javascript中创建一个新对象(使用简单继承),以便从变量定义对象的类:
var class = 'Person';
var inst = new class
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
med*_*iev 29
你可以做点什么
function Person(){};
var name = 'Person';
var inst = new this[name]
Run Code Online (Sandbox Code Playgroud)
关键是引用拥有构造函数的对象.这在全局范围内工作正常,但如果您将代码转储到函数内部,则可能必须更改引用,因为this可能无法工作.
编辑:传递参数:
function Person(name){alert(name)};
var name = 'Person';
var inst = new this[name]('john')
Run Code Online (Sandbox Code Playgroud)
这是我如何做到的.与meder的答案类似.
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');
Run Code Online (Sandbox Code Playgroud)