我想在JavaScript中创建一个新对象(使用简单继承),使得对象的类是根据变量定义的:
var class = 'Person';
var inst = new class
有什么想法吗?
我想在JavaScript中创建一个新对象(使用简单继承),使得对象的类是根据变量定义的:
var class = 'Person';
var inst = new class
有什么想法吗?
function Person(){};
var name = 'Person';
var inst = new this[name]
关键在于引用拥有构造函数的函数对象。这在全局范围内运行良好,但如果你将代码放在函数内部,则可能需要更改引用,因为this
可能无法工作。
编辑:要传递参数:
function Person(name){alert(name)};
var name = 'Person';
var inst = new this[name]('john')
以下是我的做法,与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');
className
作为参数传递给父函数,从而由于暗示方法而使用任何类。至少我设置的方式是这样的。 - Barrynew
:class Person{}
const class_type = Person;
const instance = new class_type();
console.log("works?", instance instanceof Person); // true
为了在meder上面的答案基础上进行改进:
使用函数调用:
你只需要用包含所引用类的作用域替换 'this',例如,如果该类是在全局作用域中编写的,如下所示:
function Person(name){alert(name)};
var name = 'Person';
function classMaker(){
var inst = new window[name]('john');
}
classMaker();
我在Node.js中遇到了类似的问题,当我需要根据数据动态创建不同的处理程序对象时。首先,我将所有可用的处理程序(作为单独的模块实现)收集到一个对象中。在简单情况下,可以像这样硬编码。
var handlers = {
handlerX : require('HandlerX'),
handlerY : require('HandlerY')
};
然后,每当我需要实例化处理程序时,我都会这样做:
var handlername = getHandlerName()
var handler = new handlers[handlername]();
apply
方法传递参数,这在你事先不知道参数时非常有用,例如:this[name].apply(null, args)
,其中args是一个参数/参数数组。当动态调用函数时,这种情况似乎更常见。 - Jamie Treworgy