Javascript从字符串动态调用对象方法

Mik*_*ite 85 javascript oop methods dynamic invoke

我可以动态调用方法名称为字符串的对象方法吗?我会想象它是这样的:

var FooClass = function() {
    this.smile = function() {};
}

var method = "smile";
var foo = new FooClass();

// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();
Run Code Online (Sandbox Code Playgroud)

Kar*_*ath 195

如果属性的名称存储在变量中,请使用 []

foo[method]();
Run Code Online (Sandbox Code Playgroud)

  • 你是一个传奇! (9认同)
  • 得到这个丑陋的错误“元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“FooClass””其他人? (3认同)
  • 在函数中使用变量对我不起作用:const genericResolver = ( table, action , values ) => { return Auth.isAuthenticated() .then(() => { return eval(table).findAll() (2认同)

Did*_*hys 30

可以通过数组表示法访问对象的属性:

var method = "smile";
foo[method](); // will execute the method "smile"
Run Code Online (Sandbox Code Playgroud)


s.n*_*s.n 6

当我们在对象内部调用函数时,我们需要以字符串形式提供函数的名称。

var obj = {talk: function(){ console.log('Hi') }};

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
Run Code Online (Sandbox Code Playgroud)

  • 为您的代码提供一些注释总是很有帮助的,这样就可以脱离上下文来理解它。 (2认同)

小智 5

可以使用 eval 调用方法 eval("foo." + method + "()"); 可能不是很好的方法。