0

我在我的视图对象中将我的 self 方法引用为 this.removeThanksContainer 这通常很好,但是当我在我的 $.post() 回调中时,对的引用this成为全局窗口对象而不是我的视图...... .

    removeThanksContainer : function() {
        var $thanksContainer = $('#js-review-thanks');

        $thanksContainer.is(':visible') && $thanksContainer.remove();
    },

    getProductInfo : function(evt) {
        // local method
        var removeThanksContainer = this.removeThanksContainer;

        $.post(postURL, { product_id : productId }, function(data) {
            if (data) {
                removeThanksContainer();
            }
        }, 'json');
    }

因此,作为一种解决方法,我将对该方法的引用保存到 getProductInfo 中的局部变量,var removeThanksContainer = this.removeThanksContainer;以便在 $.post() 中访问它。这是做到这一点的最佳方法还是有首选/更好的方法?

谢谢。

4

2 回答 2

0

您还可以保留对this喜欢的参考

var that = this;

并调用回调that.removeThanksContainer();$.post

于 2012-11-29T20:50:17.640 回答
0

你可以使用这样的东西

function myClass()
{
    var self=this;
    ....
    getProductInfo : function(evt) {
        // local method
        var removeThanksContainer = self.removeThanksContainer;
        // or call it directly without any reference you have kept above
        self.removeThanksContainer();
    }
}
于 2012-11-29T20:50:44.180 回答