JS 方法绑定 2 个不同的 this

JS method binding with 2 different this

我有这个小代码:

ScenesController.prototype.viewAction = function() {
    this.flash = this.di.HelperFlash.hasSupport();

    this.$playerElem = !this.flash? $('#html_player') : $('#flash_player');
// the first click is just a sample, I need the same object in the Quailty Change method
    $('.scenes_view_video_quailty').on('click', function() { echo($(this));});
    $('.scenes_view_video_quailty').on('click', this.viewVideoQuailtyChange.bind(this));

};
ScenesController.prototype.viewVideoQuailtyChange = function(e) {
    e.preventDefault();
    if (!this.flash) {
        echo(this);
        echo($(this));
    }
};

当我单击 link 时,我需要将此变量传递 2 给 QualityChange 方法。一个是对象(在绑定中),另一个是点击事件,因为我也需要被点击的元素。

我尝试使用 .on('click', {$this: $(this)}, this.method) 解决方案,但没有用 evend.data。 $这看起来是一个不同的对象。

我需要与第一次单击方法中相同的对象。 (echo = console.log)

将引用当前实例的 this 别名化为其他东西(传统上,self)并使用 this 引用被点击的元素

ScenesController.prototype.viewAction = function() {
    var self = this;
    this.flash = this.di.HelperFlash.hasSupport();

    this.$playerElem = !this.flash? $('#html_player') : $('#flash_player');

    $('.scenes_view_video_quailty').on('click', function() { echo(self, $(this));});    
};

要调用方法设置它是 this 参考,您将使用 Function.apply,例如:

$('.scenes_view_video_quailty').on('click', function(){
         self.viewVideoQuailtyChange.apply(self, [$(this)])
});

您可以使用 bind 附加任意数量的变量 你可以有一个合适的方法,比如:

ScenesController.prototype.viewVideoQuailtyChange = function(secondThis) {
}

然后将绑定用作:

this.viewVideoQuailtyChange.bind(this, $(this));

尽管使用此解决方案,您确实会失去事件,因此可能需要更多考虑。我会调查并更新答案:)