Call Site Matters
this depends on how a function is called, not where it is defined.
In methods, this refers to the object before the dot.
JavaScript Tutorial
The this keyword refers to the object a function is called on.
Its value changes based on the call site.
Misunderstanding this is a common source of bugs.
Knowing how this works makes methods and callbacks safer.
obj.method()
fn.call(obj)
fn.bind(obj)const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
console.log(user.greet());this refers to user.
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
const fn = user.greet;
console.log(fn());this is undefined in strict mode when detached.
this depends on how a function is called, not where it is defined.
In methods, this refers to the object before the dot.
Arrow functions do not have their own this.
They capture this from the surrounding scope.
Losing this happens when you pass a method as a callback.
Use bind, call, or arrow wrappers to keep context.
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
const bound = user.greet.bind(user);
console.log(bound());bind fixes the context.
const team = {
name: "Blue",
members: ["A", "B"],
list() {
return this.members.map((m) => this.name + "-" + m);
}
};
console.log(team.list());Arrow function uses outer this.
Without
const fn = user.greet;
fn(); // this is undefinedWith
const fn = user.greet.bind(user);
fn(); // this is userArrows do not bind this; use method syntax instead.
Bind the method or wrap it in a function.
In strict mode, this is undefined in standalone calls.
The way a function is called.
To lock this to a specific object.
No, arrows use lexical this.
Practice: Fix a method call so this refers to the object.
const user = { name: "Ava", greet() { return "Hi " + this.name; } };
const fn = user.greet;
// TODO: call with correct this
One Possible Solution
const user = { name: "Ava", greet() { return "Hi " + this.name; } };
const fn = user.greet.bind(user);
console.log(fn());It depends on how the function is called.
No, they capture this from their scope.
Use bind or arrow functions.
Try detaching methods and see how this changes.