'this' and its ever changing context.
Joshua Ng'ang'a Raphael
Posted on February 21, 2024
The this keyword is a special keyword associated mainly with the languages C++, Java and JavaScript. It however varies in application between the three languages, with 'this' being used quite similarly in Java and C++ to refer to the current object within instance methods.
'this' in C++
When used in c++, the keyword 'this' is used as a pointer that points to the object whose member function is being executed. It holds the memory address of the current object and accesses members of the current object within member functions
#include <iostream>
class NewClass {
public:
int num;
void printVal() {
std::cout << "Value of val is: " <<this->val << std::end1;
}
};
int main() {
NewClass obj;
obj.val = 36;
obj.printVal(); // Value of num is: 36
return 0;
'this' in Java
Just as in C++, 'this' is used in Java to refer to the current object instance to access members of the current object within the object instance methods
public class NewClass{
int x;
public void printX() {
System.out.printIn("Value of x: " + this.x);
}
public static void main(String[] args) {
NewClass obj = new NewClass();
obj.x = 46;
obj.printX(); // Expected Output: Value of x: 46
}
}
As seen in the examples, the this keyword accesses the object members val(36) in C++ and x(46) in Java within member functions of the objects.
The 'this' keyword in JavaScript however, is applied dynamically depending on the scope and context in which the function containing the 'this' keyword is invoked.
'this' in JavaScript
As earlier discussed, the this keyword will refer to different objects depending on its current scope and context. As a result 'this' can be applied in various contexts to bring about different meaning as discussed below
- 'this' in Global context- when not used within a regular function, object or constructor function, 'this' is placed in global scope. Simply put, in JavaScript we consider functions to be treated as objects; hence the keyword 'this' will be called in the global scope provided it is outside of any object and it will instead refer to the global object. The global object in browsers is referred to as the window and can be output by logging 'this' in the console.
- 'this' in method invocation - a function that is defined as a property of an object is called a method and when it is called, it is invoked as a method of an object. In this case, 'this' refers to the object in which the method is a property.
let obj = {
name: 'Unai',
greet: function() {
console.log('Good evening, ' + this.name);
}
};
obj.greet(); // Output: Good evening, Unai
- 'this' in constructor invocation - we use constructor functions to create multiple instances of objects. If the constructor function used to create an instance of an object is invoked with the 'new' keyword and the arguments to be used as the properties of the new object are passed , 'this' is now used to refer to the newly created object.
// Constructor function
function Vehicle(name) {
this.name = name;
}
let vehicle1 = new Vehicle('Audi');
console.log(vehicle1.name); // Output: Audi
Constructor invocation and callback functions
Special cases may be encountered when using callback functions within constructor functions.
As shown in this example, the expected output which is the new instantiated object is not logged. Rather, the window objected is returned indicating that the 'this' keyword is referring to the global object instead of the 'me' object.
This confusion is brought about by the callback function which is executed in an entirely different context to the constructor function as it is not defined as a method of the constructor despite being written within it.
The callback function can be however made to execute in the same context as the constructor by binding the 'this' object to the function.
This is an example of explicit binding and its benefits which we take a deeper look into as the next context in which 'this' is used.
- 'this' in explicit binding - explicit binding is the clear and direct process of specifying the value of 'this' within a function using functions such as 'call' or 'bind'
function useName() {
console.log('My name is ' + this.name);
} //this is used within a function
let person2 = { name: 'Josh' };
useName.call(person2); // Output: My name is Josh
Here explicit binding using 'call()' allows us to specify the value of the keyword 'this' as the object 'person2'.
Despite the confusing variability of the 'this' keyword in JavaScript, a good tip to keep at the back of your mind is that the 'this' keyword will always refer to the object that is currently executing or invoking the function where 'this' is used.
In this article we have tried to elaborate on the various use cases of the 'this' keyword. By reaching the end of this article, you should hopefully be able to interpret the context of 'this' the next time you encounter it.
Posted on February 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.