changing function’s context in javascript
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.