changing function’s context in JavaScript

by MichaƂ Kuklis on 31/10/2009

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.

No comments yet.

Write a comment: