How best would you describe JavaScript? To the regular joe, JavaScript often referred to as JS as we would in most parts of this article, is a scripting or programming language that allows for client-based interaction like animations and general web-based interactivity. Though JS can be used as a server-side technology, in the case of NodeJS, such conversation is beyond the scope of this article. The question that should be on your mind should be, what topic is within the scope of this article? If you answered this
, you will be 100% correct the this
keyword In JavaScript will be discussed to simplify its usage or application.
While JS is in a love-hate relationship with the general programming community (especially with beginners), we will throw more light on why the this
keyword is unavoidable and important to know.
What is this?
In the JavaScript programming language, this
refers to an object. The conflict usually arises from which object it refers to, but this totally depends on how it is invoked or called. Before proceeding, we have thrown around the word object, and understanding objects in JS are critical to properly understanding this
.
Objects in JS are independent entities (form) with properties and type. For example, a dog can be an object with barking, walking, and running properties, with the colour of its fur also being one of its properties. In simple terms, properties define the characteristics of objects.
Example:
Right-click on your browser, select inspect then the console tab and enter the following codes below.
const myCar = {
make: ‘Honda’,
model: ‘Accord’,
year: 2006,
color: ‘Black’
};
You can call or reference the property by entering the code below:
myCar.color
it returns
‘Black’
Note: This is just one way of declaring objects in JavaScript and if a property that does not exist is called it returns undefined.
We have spent some time discussing a non this
idea, but it was worth it, so let us head back to this
and the general concept behind it.
In general terms this
references the object calling the function, meaning this
is defined by the object making the interrogation or call, and not the function.
Following the previously mentioned steps above, type this
in your console and you will get the following output, referencing the windows global object.
Window {window: Window, self: Window, document: document, name: '', location:
Location, …}
This can be expanded to see other properties tied to the global window object of your browser the window property of a Window object points to the Window object itself. This means the following codes below when entered in the console environment will all return the window object.
window
window.window
window.window.window
Window {window: Window, self: Window, document: document, name: '', location:
Location, …}
If we were to type this.location
, it will return the current URL and other properties associated with it, same with window.location
as shown below.
Location {ancestorOrigins: DOMStringList, href: 'https://esodora.com/', origin:
'https://esodora.com', protocol: 'https:', host: 'esodora.com', …}
To paint a clearer picture, the following points need to be understood and come to terms with.
1. this is a reserved keyword and cannot be used as a variable: like other programming languages, reserved keywords are kept for the language and its internal running, users are not allowed to reference them for storage as variables and the same can be said about this keyword. The code below will throw a syntax error.
let this = 'you cannot use as variable'
Uncaught SyntaxError: Unexpected token 'this'
2. When this is used in an object method, it references the object: the code below clearly illustrates the title.
const myCar = {
brand: "Honda",
model: "accord",
year: 2006,
details : function() {
return this.brand + " " + this.model + " " + this.year;
}
};
myCar.details()
returns
'Honda accord 2006'
3. When this is used alone, it references the global object as shown in the widow example above: this section requires no further explanation as it has already been shown above to return the global window object.
4. When used in a function, this references to the global window object, same as when used as a stand-alone.
function validate(){
return this == window;
}
validate();
true
5. In strict mode, this keyword returns undefined, and this is because in strict mode the global object refers to undefined rather than the window object.
"use strict"
function callThis(){
console.log(this);
}
undefined
callThis()
undefined
6. In events, this refers to the element that received the event, this might be a little tricky, we will need to go a little bit further and create a simple HTML page.
<!DOCTYPE html>
<html>
<body>
<button onclick="this.style.backgroundColor='red'"> CHANGE COLOR </button>
</body>
</html>
You can test out this markup by simply creating a .html
page and double-clicking on it.
7. Methods like call(), apply(), and bind() can refer to this in any object.
• call() and apply(): the call()
and apply()
method with close similarities, meaning they can call an object while passing another object as the argument of the object initially called. The obvious difference between call()
and apply()
method lies with how they take arguments. The call()
method accepts arguments as separate values while the apply()
method makes use of arrays for arguments. As illustrated in the examples below:
call() Example:
const buyer = {
printForm: function() {
return this.fullName + " bought a " + this.model + " for " +this.price ;
}
}
const details = {
fullName:"Chidi E. Egwu",
model: "Tesla",
price: 50000,
}
buyer.printForm.call(details);
the above code returns
'Chidi E. Egwu bought a Tesla for 50000'
You can see that the call() methods take a single object as an argument.
apply() Example:
const buyer = {
printForm: function(model, price) {
return this.fullName + " bought a " + model + " for " + price;
}
}
const details = {
fullName:"Chidi E. Egwu",
}
buyer.printForm.apply(details, ['Tesla', 50000]);
the above code returns the same result as the call() method, but it does it using multiple arguments as earlier explained.
'Chidi E. Egwu bought a Tesla for 50000'
• bind(): the bind method allows you to borrow across functions, the example below will better explain this statement.
Example:
const buyerForm = {
fullName:"Chidi E. Egwu",
model: "Tesla",
printForm: function() {
return this.fullName;
}
}
const salesAgent = {
fullName:"Dorathy James",
}
let printAgent = buyerForm.printForm.bind(salesAgent);
printAgent();
The salesAgent object borrows printForm method from the buyerForm object and makes use of it in returning the fullName of the agent.
Summary
This article draws your attention to the various applications and usage of the this keyword in JavaScript; while not exhaustive, it can be used as a reference or steppingstone for beginners encountering the JavaScript mysterious this
keyword for the first time. Whatever your reason for reading this article, I hope I was able to answer, if not all, at least the majority of your questions about getting started with and understanding the fundamentals of this keyword in JavaScript.
Top comments (1)
Found this helpful! Thank you