this keyword - kdaisho/Blog GitHub Wiki
Remembering the behavior of the this keyword can be tricky, so here's a quick reference:
In regular functions, the value of this is determined by the object on which the function is invoked.
function logThis() {
console.log(this)
}
const obj = {
logThis
}
logThis() // window
obj.logThis() // objFor arrow functions, this is determined by the lexical environment in which the arrow function is defined.
const logThis = () => {
console.log(this);
};
const obj = {
logThis
}
logThis() // window (where the function was defined)
obj.logThis() // window (where the function was defined)The value of the this keyword is constructor functions or classes is the value of the newly created instance.
class User {
getThis() {
return this
}
}
const user1 = new User()
const user2 = new User()
user1.getThis() // user1
user2.getThis() // user2The value of the this keyword is undefined on Window object by default. The behavior from "use strict" keyword automaitcally applies in modules. So if you're using ESM, this will be undefined on Window by default.
"use strict"
function logThis() {
console.log(this)
}
const obj = {
logThis,
logThis2() {
logThis()
}
}
logThis() // undefined
obj.logThis() // obj
obj.logThis2() // undefinedThe value of the this keyword is event handlers using a regular function is the element that received the event.
button.addEventListener("click", function() {
console.log(this)
})
button.click() // <button>...</button>The value of the this is determined by the lexical environment in which the arrow function is defined.
button.addEventListener("click", () => {
console.log(this)
})
button.click() // windowCalls a function with a given this value. (Invokes the function)
Creates a new function with a specified this value and optional initial arguments. (Doesn't invoke the function)
Calls a function with a given this value and arguments provided as an array. (Invokes the function)
function greet(text = "Welcome") {
console.log(`${text}, ${this.username}`)
}
greet.call({ username: "John" }) // Welcome, John
greet.bind({ username: "John2" })() // Welcome, John2
greet.apply({ username: "John3" }, ["Hey"]) // Hey, John3