通过变量动态实例化一个类 [英] Instantiate a Class dynamically via variable

查看:83
本文介绍了通过变量动态实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过抛出变量名来实例化一个类? 在类中考虑此方法:

How can I instantiate a class by throwing in a variable name? Consider this method inside a class:

animate: function(el, build) { 
        console.log(build.effect); 
        var animationClass = new build.effect(el,build); 
}, 

Build是一个包含很多东西的对象,但最重要的是 影响".此效果是独立动画类的名称- 一种叫做"MarioKartMenu".

Build is an object containing lots of stuff, but most importantly an "effect". This effect is the name of an independent animation class-- one is called "MarioKartMenu".

console.log(build.effect)打印出"MarioKartMenu". 但是我当然知道了:TypeError:表达式'build.effect'的结果[MarioKartMenu]不是构造函数.

console.log(build.effect) prints out "MarioKartMenu". But of course I get: TypeError: Result of expression 'build.effect' [MarioKartMenu] is not a constructor.

如果我放弃了动态性,只需编写如下代码:

If I trash the dynamism and just make the code as such:

animate: function(el, build) {
        var animationClass = new MarioKartMenu(el,build);
    }, 

效果很好.是否有可能像我尝试的那样使它动态化?

It works just fine. Is it possible to make it dynamic like I'm attempting to do?

推荐答案

如果函数MarioKartMenu是在全局范围内定义的,则可以使用以下字符串的字符串名称来访问它:

If the function MarioKartMenu is defined in the global scope, you can access it by its string name using:

window["MarioKartMenu"]

之所以可行,是因为所有全局变量都是window对象的属性.

This works because all global variables are properties of the window object.

鉴于上述情况,您可以使用以下方法实现所需的功能:

Given the above, you can implement what you want by using:

var menuConstructor = window[build.effect];
var animationClass = new menuConstructor(el, build);

这篇关于通过变量动态实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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