1

If I pass a function as an argument, and the function is a jQuery method, will calling the passed function later still correctly set this? I thought it would, but calling the function later has this = Window.

Example code:

var $input = $('input').first();

var evaluators = [];

evaluators.push($input.val);

_.forEach(evaluators, function(valueMethod) {
    return valueMethod() //returns undefined always since this = window
}).
Tahsis Claus
  • 1,669
  • 1
  • 12
  • 24

2 Answers2

3

Try using bind:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

evaluators.push($input.val.bind($input)); 

It is worth noting bind is not supported on older browsers (e.g. IE8 and FF3 (or older)).

mbinette
  • 4,884
  • 3
  • 22
  • 31
  • That is what I was expecting to have to do. Does that mean JS only sets `this` properly if you call the function directly from the object instance like `obj.prototypeMethod()`? – Tahsis Claus Sep 29 '15 at 18:33
  • You are right, I have added a link to a compatibility table – mbinette Sep 29 '15 at 18:35
  • That is correct. Basically, what `input.val` refers to is the function itself, without it's context (e.g. the prototype method). The context is passed when you make the call. What `bind` does is create a new function which wraps around the original one, defining the context passed as a parameter. – mbinette Sep 29 '15 at 18:40
0

Please refer to jQuery.proxy() to see how context or this of the function can be set.

mdr
  • 16
  • 4