【问题标题】:Unclear on melonJS use of callback不清楚 melonJS 使用回调
【发布时间】:2014-03-12 05:26:52
【问题描述】:

this melonJS tutorial 之后,我对这个回调的几种使用方式感到困惑(向下滚动到第 2 部分:加载我们的关卡,您将看到完整的代码)

// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);

我读过this tutorial on callbacks,所以我明白它们的用途……但我不明白。它说this.loaded.bind(this)

1) 第一个和第二个this 语句有什么区别

2) 做什么bind 和传递(this) 做什么?

谢谢

【问题讨论】:

    标签: javascript callback bind melonjs


    【解决方案1】:

    .bind(this) 设置函数的上下文

    如果只设置为this.loaded,则不保留上下文

    这可能更有意义

    var cntx = this;
    me.loader.onload = function() {
      cntx.loaded();
    }
    

    但是,在此示例中,没有参数传递给 loaded 函数。通过使用 bind 单行符,您可以保留上下文,并且您不必担心在此过程中会丢弃任何参数。

    在此处了解Function.prototype.bind

    【讨论】:

    • 在这种情况下this 是什么,上下文是什么意思?
    • @Growler,请阅读this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2011-11-14
    • 2018-03-17
    • 2016-06-16
    • 2013-09-28
    相关资源
    最近更新 更多