JavaScript Context is Actually Easy to Understand

js-150x150One of the most misunderstood concepts of JavaScript is the context topic. When saying context I’m referring to the ‘this’ keyword inside a function.
Now let’s break that down:

If it is a constructor than the ‘this’ keyword will refer to the newly created object.
So when creating an object with the ‘new’ keyword the context of the ‘this’ keyword is the new object that was created. But if the function would have been called without the ‘new’ keyword than the context would be the global context meaning the global ‘window’ object

On an object the context is the object the function is executed on. Sounds confusing? A simple example will clear that out:

That is it! It is simple as that. So, why the confusion? Things can go a bit more complex when we want to use a different context than the current one. Let’s look at an example:

I used  the context var here because that inside the ‘dat’ function we have a new context so if we used the this keyword instead of the context variable then it would refer to ‘obj.doo’ instead of just ‘obj’

Another exception of context is the ability to control the context inside a function. Using the call and apply method of JavaScript we can set the context:

The call function first parameter is the context that will be available as the this keyword inside the called function. the rest of the parameters – will be the original function parameters:

The difference between call and apply is the way the parameters are passed:

These two calls are equivalent, the apply function parameters are just passed as an array. Why do we need that? well, sometimes we have the data as an array and this will save as the conversion, no other difference besides that.

Hope this was clear… Have Questions? contact me! or post a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">