首页 > 解决方案 > 当名称为字符串时,在类中调用静态 JavaScript 函数

问题描述

我可以动态调用名称为字符串的静态函数吗?经过一番尝试,这就是我所能得到的:

   class Test{
        static Instance(){
          console.log( "Instantiated" );
        };
    };

    Test.Instance();//<-- ok

    var testVar = "Test";

    eval( testVar + ".Instance()" ); // ok but eval is evil!

    window[testVar].Instance();//<-- undefined is not an object (evaluating 'window[testVar].Instance')

标签: javascriptclass

解决方案


你可以使用new Function

堆栈片段

class Test {
  static Instance() {
    console.log("Instantiated");
  };
};

var testVar = "Test";

var func = function(string) {
  return (new Function('return (' + string + ').Instance()')());
}

func(testVar);


这是一些关于new Function比较的阅读eval


推荐阅读