JavaScript ‘this’ Keyword

The ‘this’ keyword in JavaScript is used to refer to the current object; the next highest object that defines the scope of the current context. It can be quite difficult to work out what ‘this’ will refer to within JavaScript. Remember it refers to an object, not the current scope.

The below code shows setting the value of two variables to the return result of the ‘this’ keyword. One variable is initialised within the global scope and the other is set within the scope of a function. However, both of these variables will be set the the same value, the global object. This is because the variable ‘a’ is within the global scope, and the function is called within the global scope. The last line of the code snippet is calling the function within the global scope object, so this is the next highest object that is in scope. This is why both ‘this’ keywords are equal to the global scope object.

The function is an example of an object function within JavaScript, that sets two internal variables. The use of the ‘this’ keyword is used to attached variables to the object. However, if this function is called in the global scope then the ‘this’ keyword will refer the global object, just like the above example.

We can also add internal functions within the object function, such as below which is used to return a concatenation of the two internal variables. Unlike the first example, the Person function is create as an object using the ‘new’ keyword. This means in regards to the usage of the ‘this’ keyword the newly created Person instance is the next highest object in scope. That means the ‘this’ keywords used within the Person function, within the created instance, will refer to the instance object of the Person, rather than the global object. Meaning, the internal variables are attached the instance object rather than the global object, as it is initialised using the ‘new’ keyword to create an object.

The ‘this’ keyword is used in JavaScript to reference the next highest level object in scope, either an instance of a functional object or the global object. The ‘this’ keyword only refers to objects, so even when used inside a function it will refer to the object that function is called within rather than the function itself.

Leave a Reply