将此传递给回调

时间:2013-09-16 15:53:51

标签: javascript

我知道问题是什么,但不确定什么是解决此问题的最佳选择。我有一个回调,但我无法从中访问this。我不希望在范围之外有任何变量来引用它。我可以将this作为参数传递吗?

    var myModule = Module.create({

           init: function() {
                ws.subscribe('/topic/notifications', this._wsNotifications, headers);
           },

            refresh: function() {
            },

            _wsNotifications: function ( message ) {
                 this.refresh();  //Error: 'this' is undefined because it's a callback
             }
        });

3 个答案:

答案 0 :(得分:2)

您可以使用ECMAscript的bind function Function.prototype.bind

init: function() {
            ws.subscribe('/topic/notifications', this._wsNotifications.bind(this), headers);
       },

现在,this中的_wsNotifications将引用您绑定的对象。

答案 1 :(得分:2)

您可以解决此问题的一种方法是在源代码中使用function.bind指定回调时执行

  ws.subscribe('/topic/notifications', this._wsNotifications.bind(this), headers);

或将this缓存到变量。

 var myModule = Module.create({
       self  : this,
       init: function() {
            ws.subscribe('/topic/notifications', this._wsNotifications, headers);
       },

        refresh: function() {
        },

        _wsNotifications: function ( message ) {
             self.refresh();  //Error: 'this' is undefined because it's a callback
         }
    });

答案 2 :(得分:2)

试一试。

var myModule = Module.create({

       var self = this;

       init: function() {
            ws.subscribe('/topic/notifications', this._wsNotifications, headers);
       },

        refresh: function() {
        },

        _wsNotifications: function ( message ) {
           self.refresh();  //Error: 'this' is undefined because it's a callback
        }

    });

    return interactions;
});

请注意self变量的创建和使用,而不是this变量。使用此方法将保留this,即使它通常会更改范围。

相关问题