【问题标题】:javascript bindingjavascript绑定
【发布时间】:2010-05-09 03:02:27
【问题描述】:
MyObj = 
{
    ajax: null,
    init: function()
    {
        this.ajax = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
           .createInstance();
        this.ajax.onload = function()
        {
            return function() {this.onload.apply(this, [null]);}
        };
    },
    onload: function ()
    {
        Reader.log("I really hope I can use `this.ajax` here");
    }
}

将 onload 绑定到 MyObj 不是正确的方法吗?由于某种原因,onload 从未调用过。但是,如果我避免绑定并只输入this.ajax.onload = this.onload,则调用onload。如何进行绑定工作?

【问题讨论】:

    标签: javascript binding


    【解决方案1】:

    我会回答自己...

    我应该调用函数

    var me = this;
    
    this.ajax.onload = (function()
            {
                return function() {me.onload.apply(me, [null]);}
            })();
    

    【讨论】:

    • 为什么会有额外的函数包装? this.ajax.onload = function() {me.onload.apply(me, [null]);}
    • @Joshua:你说得对,那是不必要的,即使没有它也能正常工作。
    猜你喜欢
    • 2017-12-20
    • 2010-12-29
    • 1970-01-01
    • 2016-07-10
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多