this?In JavaScript, this refers to the execution context โ or how a function is called, not where itโs defined.
console.log(this); // In browser: window; In Node.js: {}
function show() {console.log(this);}show(); // In non-strict mode: window (or global), in strict mode: undefined
const user = {name: "Daniel",greet() {console.log(this.name);}};user.greet(); // "Daniel"
In object methods,
thisrefers to the object the method is called on.
thisconst user = {name: "Daniel",greet: () => {console.log(this.name);}};user.greet(); // undefined
Arrow functions do not bind their own
this. They inherit it from the lexical scope (i.e. the place they were defined).
If defined globally,thisis the global object (orundefinedin strict mode).
class Person {constructor(name) {this.name = name;}sayHi() {console.log(this.name);}}const p = new Person("Daniel");p.sayHi(); // "Daniel"
In class methods,
thisrefers to the instance.
const btn = document.querySelector("button");btn.addEventListener("click", function () {console.log(this); // the button element});
If you use a regular function in an event listener,
thisrefers to the DOM element.
If you use an arrow function,thiswill refer to the outer context, not the element.
Want a quiz or coding challenge with tricky this examples? ๐