使用字符串调用方法(而不是函数)



注意:如果dup显示了如何使用类和方法而不仅仅是函数进行求解,请随时将其标记为dup。

我正在构建一个命令行工具,它从用户那里请求字符串输入,然后尝试用匹配的方法和参数调用一个类。我该如何调用才能定义它?

我有一门课:

class MyClass {
constructor() {
this.foo = 'bar';
}
myMethod(param) {
console.log(param, this.foo);  // this is undefined, based on how I invoke it
}
}

我想这样做,一旦我得到用户输入。。。

let userInputMethod = 'myMethod';
let userInputParam = 'param';
const myInstance = new MyClass();
const method = myInstance[userInputMethod];
method(userInputParam);  // error, because I need somehow to set the context of this

您可以将其绑定到

let userInputMethod = 'myMethod';
let userInputParam = 'param';
const myInstance = new MyClass();
const method = myInstance[userInputMethod].bind(myInstance)
method(userInputParam);

但在这一点上,为什么不使用普通物体呢?

// foo.js
const foo = "bar";
const hey = {
myMethod(param) {
console.log(param, foo);
},
};
//main.js
let userInputMethod = 'myMethod';
let userInputParam = 'param';
const method = hey[userInputMethod];
method(userInputParam);

如果你需要你的类接收数据,你可以使用类似的闭包

function makeInstance({ foo }) {
return {
myMethod(param) {
console.log(param, foo);
},
};
}

this上下文丢失,您需要bind它。

class MyClass {
constructor() {
this.foo = 'bar';
}
myMethod(param) {
console.log(param, this.foo);
}
}
let userInputMethod = 'myMethod';
let userInputParam = 'param';
const myInstance = new MyClass();
const method = myInstance[userInputMethod].bind(myInstance); // bind
method(userInputParam);

或者可以使用箭头功能。

class MyClass {
constructor() {
this.foo = 'bar';
}
myMethod = (param) => {
console.log(param, this.foo);
}
}
let userInputMethod = 'myMethod';
let userInputParam = 'param';
const myInstance = new MyClass();
const method = myInstance[userInputMethod]
method(userInputParam);

相关内容