dup 發現者注意:如果 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
uj5u.com熱心網友回復:
背景關系丟失了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);
uj5u.com熱心網友回復:
你可以系結它??
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);
},
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446722.html
