In this article, we will explore the differences between traditional methods and arrow functions using the following code snippet.
Example
const obj1 = {
log() {
console.log("Object 1 works", this);
},
};
obj1.log();
const obj2 = {
log: () => {
console.log("Object 2 works", this);
},
};
obj2.log();
The obj1
uses the traditional method declaration syntax for defining methods, whereas obj2
uses an arrow function syntax to define the method.
Both objects declare a method named log
that takes no arguments and returns undefined
, they differ in the way they handle the context.
The log
method from obj1
can access the object’s properties using this
. The log
method from obj2
can’t access the object’s properties using this
. obj2
captures the this
value from the surrounding lexical scope where it is defined, not from where it is called.