Implement this BinaryTree
April 13, 2025
1 min
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,
this
refers to the object the method is called on.
this
const 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,this
is the global object (orundefined
in 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,
this
refers 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,
this
refers to the DOM element.
If you use an arrow function,this
will refer to the outer context, not the element.
Want a quiz or coding challenge with tricky this
examples? ๐
Quick Links
Legal Stuff
Social Media