这是我们通过索引获取数组的方式:
var theArray=[];
theArray['something']=="Hello!";
console.log(theArray['something']); //Print "Hello!"
现在想象同样的事情,我有一个功能,我打算称之为;像这样:
export class myClass {
public callByIndex(theIndex:string) {
//this is how it works:
this.doSomething()
//And these are the ways I need to call them:
this.theIndex //of course error!
//or
this[theIndex]; //Another Error! How to do it?
}
private doSomething (){
console.log("Yesss, I called!");
}
}
let callTest = new myClass();
callTest.callByIndex("doSomething"); //Here I give the method name!
怎么可能?
答案 0 :(得分:2)
首先,Javascript中的数组只是具有整数属性的普通对象({ }
)。因此,要使用方括号调用函数,只需将要执行的函数的名称传递给它
class Test {
dummyFunction(arg) {
console.log('dummyFunction called with argument: ' + arg);
}
}
let test = new Test();
test['dummyFunction']('this is a string');