Alex Hall Alex Hall - 6 months ago 12
Javascript Question

Why can't I store a reference to $(elem).show and call it later?

See the jsfiddle.

When I run the code below:

var divs = $('div');

// The first three methods of showing a div work
divs.eq(0).show();
(divs.eq(1).show)();
var f = function() {
divs.eq(2).show();
}
f();

// But this doesn't. Why?
var g = divs.eq(3).show;
g();


The last method doesn't show the div, and there's no error in the console. I want to use it because I want to store the function concisely without creating an anonymous function block. This is what I would normally do in Python. I can't understand what goes wrong here.

EDIT: the comments aren't really helping me understand the problem. How did
this
get lost? What did it change to and why? Why doesn't that happen with
(divs.eq(1).show)();
?

Answer

As already explained in the comments, it doesn't work because show() depends on the value of this.

The value of this depends on how a function is called:

  • When called as a "normal" function (foo()), this will refer to the global object or undefined (when in strict mode).
  • When called as object method (obj.foo()), this refers to the object (obj).

Understanding how this works in JS is crucial. See: