Alex Hall Alex Hall - 1 year ago 49
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
var f = function() {

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

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
get lost? What did it change to and why? Why doesn't that happen with

Answer Source

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 (, this refers to the object (obj).

Understanding how this works in JS is crucial. See: