Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's $.proxy vs var self - The common way to preserve the context of `this` [closed]

Tags:

jquery

What is the common way to preserve the context of this? What is faster? What would you prefer?

  1. $.proxy(...)

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

    var self = this;
    
    $('a').on('click', function() {
        self.close();
    });
    
like image 800
Aley Avatar asked Oct 21 '22 15:10

Aley


1 Answers

Let's start by fixing your code. You have a useless function declaration, you may use $.proxy as

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

Now, the second solution based on self

  • requires only basic javascript knowledge
  • doesn't require jQuery
  • is a little more readable, especially as you often reuse your self variable
  • is much faster

That's probably why it's more used.

Note that when you don't have to be compatible with IE8, you may use bind :

$('a').on('click', this.close.bind(this));
like image 57
Denys Séguret Avatar answered Nov 02 '22 08:11

Denys Séguret