Changing the context of Javascript functions

Javascript has an interesting approach towards functions.

Out of multiple fascinating features which functions possess in Javascript, one such is change of context.

Every Javascript function has inner scope which defines the current object in it. This current object in the function can be accessed using ‘this’.

So, we can write a function accessing its current context object through this and process various things on this object. Now, here is where the magic starts. In Javascript, we can change the context of a function when being called and make it shift its reference of current object to the one that is passed as an argument.

Two such functions which can be used for this in Javascript are – call and apply.

Both these functions are invoked on other functions and accept multiple arguments, where the first argument is object which would be referenced by ‘this’ in the function.

Both these functions will actually execute the function which is invoking them and would set the current context of that function to the object passed as first argument. The main difference in apply and call is that apply will accept the remaining argumentsĀ as an array, where as, call will accept the remaining arguments as comma separated list.

Thus, by invoking call or apply at a function and passing the right object as argument, Javascript acutally changes the context of that function and sets it ‘this’ reference to the object passed.

There is one more function which is used to do a similar thing – bind, which we shall see in another post.

Advertisements

One thought on “Changing the context of Javascript functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s