Set “this” variable easily?

There are two methods defined for all functions in JavaScript, call(), and apply(). The function syntax looks like:

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

What these functions do is call the function they were invoked on, assigning the value of the object parameter to this.

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );

Leave a Comment