jquery 回调中不明确的 'this'

Ambiguous 'this' inside jquery callback

我的问题是 jquery 回调中 'this' 的上下文。

$('input').on('change', function(){
    this.number = $(this).val();
});

上面,这是输入元素,通常是我们想要的 'this'。问题是,当它成为一个对象的方法时,如下所示。

// constructor pattern
var View = function(){
    this.number = 0;
};

// method definition
View.prototype.foo = function(){
    $('input').on('change', function(){
        // former this should be the object instance and 
        // the latter should be the html element.
        this.number = $(this).val(); 
    });
};

要更改函数的上下文,Function.bind() 可以如下使用。

View.prototype.foo = function(){
    $('input').on('change', function(){
        this.number = $(this).val(); 
    }.bind(this)); // bind the callback to the instance of View object
};

以上工作直到 $(this).val() 从那时起 $(this) 希望输入元素返回而不是 View 对象。

为了以临时方式解决这个问题,我可以明确地将其设置为实例名称,如下所示。

View.prototype.foo = function(){
    $('input').on('change', function(){
        // explicitly set this to be the instance
        // while sacrificing generality since code breaks when the object name is not 'view' 
        view.number = $(this).val(); 
    }); 
};

var view = new View();

如您所见,这可以解决 this 的歧义,但也会损害通用性,因为当对象名称不是 'view' 时代码会中断。

鉴于以上,我怎样才能让代码在不影响通用性的情况下解决歧义? 请提出一个方法。谢谢。

许多 lib/frameworks 中常用的方法如下:

View.prototype.foo = function(){
    var self = this; // store this as a local variable
    $('input').on('change', function(){
        self.number = $(this).val(); 
    }); 
};