Maintaining the value of 'this' when using

2019-02-28 08:18发布

I have the following function:

onDocumentKeyUp: function (e) {
    if (e.keyCode === 27) {
       this.deactivate();
    }
}

I wanted to bind this like so:

$(document).on('keyup', onDocumentKeyUp);

However, when I do that, the this inside the onDocumentKeyUp function refers to the document. I solved this by doing:

var self = this;
$(document).on('keyup', function(e) { self.onDocumentKeyUp(e); });

This works, but something tells me there's a cleaner way to pull this off. Would .call() or .apply() somehow..apply here? I'm still unsure how those functions work exactly.

Also, I don't necessarily need to limit myself to jQuery.on(). If there is a 'vanilla' way of doing this, be my guest to teach me.

2条回答
Melony?
2楼-- · 2019-02-28 09:04

You can use .bind() to set the context (without immediately calling it like call or apply):

$(document).on('keyup', this.onDocumentKeyUp.bind(this));

As this method is only supported by ES5.1-compliant browsers, you might use jQuery.proxy instead of polyfilling it.

查看更多
等我变得足够好
3楼-- · 2019-02-28 09:11

Draw your attention on data parameter of the on method here: http://api.jquery.com/on/ Also you can utilize jQuery.proxy method: http://api.jquery.com/jQuery.proxy/

Here is jsFiddle: jsFiddle

查看更多
登录 后发表回答