Friday, 14 June 2013

Understanding the "this" keyword in javascript.

Many articles and tutorials have been written about the "this" keyword in javascript, but for many of us, it had been a very difficult concept to wrap our mind around. But before i share this new perspective of mine there are some terms that need to be properly understood before the meaning of the "this" keyword sink in. These terms are : objects and compile time/runtime.

Firstly what is an object? To the common man on the street an object is anything that has attributes, properties, features and actions. This means that the physical objects we interact with in our day to day activities that have attributes like color, shape, size among other behaviors  like move, fly etc are objects. So equating this definition to the programming world and javascript object (in fact object in the general sense) has properties, attributes, method, functions(that is: actions) among other things.

Furthermore to explain the partners compile time/ runtime, compile time is the time when the programmer is writing the code (imputing the code in his favorite editor ) but runtime is the time when the code is being run in a system be it during debugging or when it have been deployed.

Enough of all that so how does it relate to the "this" keyword in javascript? If you read many of the articles online or some of the javascript text books(no names please) you will usually come across the term execution context, but what is the execution context?. Now execution context is the context or object that is currently executing during code runtime. So to simplify, the this keyword as far javascript is concerned the "this" keyword refers to the object that is currently executing. This means that you can use the "this" keyword to refer to object in the heap that is currently under execution, which can be a native object like the BOM objects (Browser Object Model), the DOM (Document Object Model), or custom objects.So to get a reference to the object's execution context, you use the "this" keyword. But be careful though because using the "this" keyword is a mine field so to speak as so many things can happen to change the execution context but more on that later.

No comments:

Post a Comment