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
  • 5,090
  • 11
  • 34
  • 41

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
  • 741,623
  • 53
  • 500
  • 612
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é
  • 69,329
  • 26
  • 129
  • 166
jbarnett
  • 984
  • 5
  • 7
  • 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
  • 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,714
  • 2
  • 18
  • 39
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
  • 22,070
  • 18
  • 81
  • 118