拉丁的傳說
2022-08-18 16:05:54
我有兩個變量要傳遞給JS回調函數(shù),一個派生自main函數(shù)。另一個是隨機內聯(lián)給定的。檢查下面的示例JS代碼,function main(callback) { st = "mainString" console.log("Execution:1 # Main function, string: " + st) callback(this.st)}function myCallback(st1, st2) { console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + st2)}main(myCallback.bind({"st1" : this.st, "st2" :" ad-hoc"}))預期輸出將低于預期值,以便兩個輸入?yún)?shù)都得到很好的處理并按順序打印。執(zhí)行:1 # 主函數(shù),字符串:主字符串執(zhí)行:2 # 回調函數(shù),st1: mainString st2: ad-hoc但我明白了,執(zhí)行:1 # 主函數(shù),字符串:主字符串執(zhí)行:2 # 回調函數(shù),st1: mainString st2: 未定義任何幫助來解決這個問題?!
2 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
改變
console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + st2)
自
console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + this.st2)
示例代碼段
function main(callback) {
st = "mainString"
console.log("Execution:1 # Main function, string: " + st)
callback(this.st)
}
function myCallback(st1) {
console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + this.st2)
}
main(myCallback.bind({"st1" : this.st, "st2" :" ad-hoc"}))

吃雞游戲
TA貢獻1829條經驗 獲得超7個贊
將綁定對象文本作為參數(shù)時,應在函數(shù)上指定上下文。根據(jù)您的條件,您只需將此關鍵字添加到 myCallback 函數(shù)中的 st2 中,如下所示:
function myCallback(st1, st2) { console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + this.st2) }
希望它有幫助
添加回答
舉報
0/150
提交
取消