General Question

lapilofu's avatar

How, in javascript/jquery, can I change what "this" refers to in an event handling function?

Asked by lapilofu (4325points) July 16th, 2009
Observing members: 0 Composing members: 0

4 Answers

philo23's avatar

By using the call and apply prototype methods of Functions.

For example:

function example () { console.log(this); }

example.call(window);
this will be the window variable.
example.call(‘a string’);
this will be a string.

Call and apply are similar to each other, they both call the function and change the scope (the “this” variable) of the function, but where they are different is that apply takes an array of parameters to push onto the function, while call takes extra arguments, for example

function testing (var1, var2) { console.log(‘var1: %o var2: %o’, var1, var2); }
testing.apply(window, [‘parameter 1’, ‘parameter 2’]);
will log “var1: parameter 1 var2: parameter 2”, to do the same with call, would be similar to this:
testing.call(window, ‘parameter 1’, ‘parameter 2’);

Hope this helps. If you need any more help with this, feel free to just ask.

lapilofu's avatar

Yeah, I was looking at call and apply, but I couldn’t quite get them to work the way that I wanted, since I couldn’t refer to my function directly. I worked out a different method, which is now at the same URL above, if anyone’s curious.

andrew's avatar

Doesn’t jquery have a bind method?

lapilofu's avatar

For binding events, not context. It’s a totally different creature from MooTools’ bind method, for instance. Just happens to be the same word. I think the theory is that .call() and .apply() are sufficient.

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther