How to set this when calling a javascript function

Ever wondered how the this entity was set in a function like for instance a jQuery event handler? Or maybe even needed to invoke that event handler from code passing the object that would be accessed through this within the function? The secret is to use the call-function that is available on every function in JavaScript.

If you for instance have an event handler setup in jQuery like the one below:
function buttonClickHandler(e) {
$(this).addClass('clicked');
}

$('a.btn').click(buttonClickHandler);
..that you would like to invoke from code and passing the object that would be accessed through this within the function, using the call-function on your event handler function will do the trick:
var btn = $('#button1');
buttonClickHandler.call(btn);

The syntax of the call-function is: call(thisArg[, arg1[, arg2[, ...]]]). The first parameter you pass is what will be accessible through the this entity. Then follows optional parameters that will be passed as parameters to the function being called in the given order.

If you which to pass an object as this to a function that takes two parameters (lets say showName(firstName, surName)) you would do it like this:
function showName(firstName, surName) {
$(this).val(firstName + ' ' + surName);
}

var element = $('#element');
showName.call(element, 'alice', 'cooper');

Related posts:

Comments

comments powered by Disqus