JQuery $ .proxy vs var self - a generic way to maintain the context of `this`

What is the general way to maintain context this? Which is faster? Which would you prefer?

  • $. Proxies (...)

    $('a').on('click', $.proxy(function() {
        this.close();
    }, this));
    
  • var self

    var self = this;
    
    $('a').on('click', function() {
        self.close();
    });
    
+5
source share
3 answers

Start by fixing the code. You have a useless function declaration, you can use $.proxyas

$('a').on('click', $.proxy(this.close, this));

Now a second solution based self

  • requires only basic javascript knowledge
  • does not require jQuery
  • we read a little, especially since you often reuse a variable self
  • much faster

This is probably why it is used more.

Please note that if you do not need to be compatible with IE8, you can use bind :

$('a').on('click', this.close.bind(this));
+2
source

Both are common.

. , 0,01 . 0,1 .

, , , , .

, , , . , .

+1

Select First. does not require an additional variable.

0
source

All Articles