In a function, any access to this refers to the controller/caller (something who called the function).
function foo() {
console.log(this);
}
foo(); // window - the caller
let bar = {
foo
}
bar.foo(); // bar - the caller
so be mindful of your usage of this. If you want to disconnect this in a class from the calling context, use an arrow function
const foo = () => {
console.log(this);
};
foo(); // {} - a empty object
In class, this refers to the object initialized from the class.
class hello {
constructor() {
this.name = 'hello';
}
foo() {
console.log(this);
}
};
const h = new hello();
h.foo(); // hello { name: 'hello' }