MyFunnyDev

web, coding and beyond

changing function’s context in javascript

without comments

Today I learned how to change the context of a function in javascript. When we do:

function test() {
  this.foo = "Hello from " + this + " context.";
}
test();
alert(foo); // will show "Hello from [object Window] context.";

foo will belong to the global context. In other words global object foo will be created. We can change the context to some other object by doing:

var otherContext = {};
test.call(otherContext);
alert(otherContext.foo); // will show "Hello from [object Object] context."

In this case foo will belong to otherContext.

Written by MichaƂ Kuklis

October 31st, 2009 at 12:24 am

Posted in Javascript

Leave a Reply