Deciphering ‘this’ in JavaScript: 5 Rules Every Developer Should Know
Essential Rules for ‘this’ Mastery: Enhance Your JavaScript Development
When writing JavaScript functions, understanding the behavior of the “this” keyword is crucial for effective programming. “this” can dynamically change its value based on how a function is invoked. Let’s explore four fundamental rules that govern the value of “this” and how they impact your code.
Rule 1: The New Kid on the Block — “new” Keyword
When a function is called with the “new” keyword, a new object is created, and “this” inside the function refers to that newly minted object.
function ConstructorFunction() {
this.property = "I am a property";
console.log(this); // Outputs: ConstructorFunction { property: 'I am a property' }
}
const newInstance = new ConstructorFunction();
console.log(newInstance.property); // Outputs: "I am a property"
// Example 2
function AnotherFunction() {
console.log(this); // Outputs: AnotherFunction {}
}
const anotherInstance = new AnotherFunction();
Rule 2: Call, Bind, Apply — The Direct Influence
When a function is invoked using `call`, `bind`, or `apply`, “this” is explicitly set to the object passed as an argument.
const myObject = {
greeting: "Hello",
greet: function (name) {
console.log(`${this.greeting}, ${name}!`);
}
};
const anotherObject = {
greeting: "Bonjour"
};
myObject.greet.call(anotherObject, "Alice");
// Outputs: "Bonjour, Alice!"
// Example 2
function customFunction() {
console.log(this); // Outputs: { customProperty: 'I am custom property' }
}
const customObject = { customProperty: "I am custom property" };
customFunction.call(customObject);
Rule 3: Object Method Invocation
In JavaScript, objects often have methods, and when a method is invoked, “this” inside the method refers to the object containing the method.
When a method is invoked on an object, “this” inside the method is bound to that object.
const car = {
brand: "Tesla",
start: function () {
console.log(`${this.brand} is starting…`);
}
};
car.start(); // Outputs: "Tesla is starting…"
// Example 2
const person = {
name: "John",
introduce: function () {
console.log(`Hi, I'm ${this.name}.`);
}
};
person.introduce(); // Outputs: "Hi, I'm John."
Window of Opportunities — Global Object and Strict Mode
If a function is called directly on the window (global object), “this” inside the function is the window object. In strict mode, it becomes undefined.
function globalFunction() {
console.log(this); // Outputs: Window object
}
globalFunction();
// Example 2
"use strict";
function strictFunction() {
console.log(this); // Outputs: undefined
}
strictFunction();
Rule 5 — The Contextual Shift — “this” in Event Handlers
In event handlers, “this” often refers to the element that triggered the event.
When a function is used as an event handler, “this” inside the function refers to the element that triggered the event.
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function () {
console.log(this); // Outputs: <button id="myButton">Click me</button>
});
</script>
// Example 2
<a href="#" id="myLink">Visit me</a>
<script>
document.getElementById("myLink").addEventListener("click", function () {
console.log(this); // Outputs: <a href="#" id="myLink">Visit me</a>
});
</script>
Conclusion: Navigating “this” with Confidence
Mastering the behavior of “this” in JavaScript functions empowers you to write more maintainable and predictable code. By adhering to these fve rules, you’ll find yourself confidently steering through the intricacies of “this” in various scenarios. Happy coding!