【问题标题】:Custom variable pass to JS callback自定义变量传递给 JS 回调
【发布时间】:2020-09-02 14:03:00
【问题描述】:

我有两个变量要传递给 JS 回调函数,一个是从主函数派生的。另一个是随机给出的内联。检查下面的示例 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"}))

预期的输出将低于,以便两个输入参数都得到很好的处理并按顺序打印。

Execution:1 # 主函数,字符串:mainString

Execution:2 # 回调函数,st1: mainString st2: ad-hoc

但我明白了,

Execution:1 # 主函数,字符串:mainString

Execution:2 # 回调函数,st1: mainString st2: undefined

任何帮助解决这个问题?!

【问题讨论】:

    标签: javascript html node.js web node-modules


    【解决方案1】:

    改变

    console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + st2)
    

    console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + this.st2)
    

    示例 sn-p

    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"}))

    【讨论】:

      【解决方案2】:

      当使用带有对象字面量的绑定作为参数时,您应该在函数中指定上下文。 根据您的情况,您只需将此关键字添加到您的 myCallback 函数中的 st2 中,如下所示:

      function myCallback(st1, st2) {
          console.log("Execution:2 # callback function, st1: " + st1 + " st2: " + this.st2)
      }
      
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-07
        • 2011-11-13
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        相关资源
        最近更新 更多