1

I often see the code like this one:

$('.element').on('click', function(event) {
  var element = this;

  // somecode that uses "element"
});

Is there any reason to cache this?

Jasper
  • 4,750
  • 10
  • 33
  • 39

4 Answers4

2

This is necessary if the code contains a closure that needs to access this. this is not a local variable, so it will not be captured in the closure, you need to bind a local variable for that purpose.

You also need it if the code contains a loop using a function like $.each(), and the body of the loop needs to refer to the element. These functions rebind this in the body to the current iteration object.

Barmar
  • 669,327
  • 51
  • 454
  • 560
2

A lot of people set a reference to this if they need to reference it in another scope of code. For example:

$('.element').on('click', function(event) {
  var element = this;

  // somecode that users "element"
  function foo() {
      //$(this).text() WONT Work!
      alert($(element).text()); //references the element that was clicked
  }
});
Fabrício Matté
  • 67,789
  • 24
  • 124
  • 163
jbarnett
  • 964
  • 4
  • 6
  • 1
    Object literal declaration does not change the `this` binding. Functions do. – Fabrício Matté Dec 24 '13 at 18:34
  • You could've used `{ text: function() { return $(this).text(); } }` in the object literal example but well, either way the example is more correct now. Just fix the "this references foo" part which you left behind. `=]` – Fabrício Matté Dec 24 '13 at 18:43
  • Good catch! Updated code. – jbarnett Dec 24 '13 at 18:45
  • I mean, the comment "this references foo" from your first example does not apply to your new example. The `this` binding for a `foo()` invocation would be `window` (or `null` in strict mode). – Fabrício Matté Dec 24 '13 at 18:47
1

Once you are inside a function or loop, this might refer to an object within that function. Therefor explicity assigning the element allows you to always access it, independent of the scope.

Neograph734
  • 1,704
  • 2
  • 17
  • 38
0

this is not a jQuery element, wrap it in $(this).

Caching is good because it stores the element, and it doesn't take up memory or processing time trying to re-find the element. However, this changes on scope so you might not want to cache that one.

Sterling Archer
  • 21,348
  • 17
  • 79
  • 113