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();
Kar*_*ath 195
如果属性的名称存储在变量中,请使用 []
foo[method]();
Did*_*hys 30
可以通过数组表示法访问对象的属性:
var method = "smile";
foo[method](); // will execute the method "smile"
当我们在对象内部调用函数时,我们需要以字符串形式提供函数的名称。
var obj = {talk: function(){ console.log('Hi') }};
obj['talk'](); //prints "Hi"
obj[talk]()// Does not work