JavaScript’s ‘this’ Keyword- Context Matters
JavaScript’s ‘this’ Keyword- Context Matters
Global Context
console.log(this); // Window
function showThis() {
console.log(this);
}
showThis(); // Window
'use strict';
function showThis() {
console.log(this);
}
showThis(); // undefined
Method Context
const person = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
person.greet(); // Alice
Constructor Context
function Person(name) {
this.name = name;
}
const person1 = new Person('Bob');
console.log(person1.name); // Bob
Arrow Functions
Explicit Binding
function showName() {
console.log(this.name);
}
const person1 = { name: 'Dan' };
const person2 = { name: 'Eve' };
showName.call(person1); // Dan
showName.apply(person2); // Eve
Example: bind
const person = {
name: 'Frank',
greet() {
console.log(this.name);
}
};
const greet = person.greet.bind(person);
greet(); // Frank
Event Handlers
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // <button id="myButton">Click me</button>
});
Conclusion
Happy coding!