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 );

I think you're looking for call:

myFunction.call(obj, arg1, arg2, ...);

This calls myFunction with this set to obj.

There is also the slightly different method apply, which takes the function parameters as an array:

myFunction.apply(obj, [arg1, arg2, ...]);

If you want to 'store' the this value to a function so that you can call it seamlessly later (e.g. when you don't have access to that value anymore), you can bind it (not available in all browsers though):

var bound = func.bind(someThisValue);

// ... later on, where someThisValue is not available anymore

bound(); // will call with someThisValue as 'this'

My search on how to bind this brought me here so I am posting my findings: In 'ECMAScript 2015' we can also set this lexically using arrow functions to.

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Instead of:

function Person() {
  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    this.age++;
  }.bind(this), 1000);
}

We can now do:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();