FE Interview Question - Guess the output II
The following code snippet is written in JavaScript and it demonstrates the use of arrow functions in objects.
// Driver code
import './style.css';
// Start here
let lol = {
name: 'Andrew Tate',
first() {
console.log(this.name + ' Loves AngularJS');
},
second: () => {
console.log(this.name + ' Loves himself. F Frameworks.');
},
};
lol.first();
lol.second();
The expected output of this code snippet is:
Andrew Tate Loves AngularJS
undefined Loves himself. F Frameworks.
The first method 'first()' is a standard object method that uses the 'this' keyword to access the 'name' property of the 'lol' object and logs it to the console. Therefore, it returns the expected output of "Andrew Tate Loves AngularJS".
The second method 'second()' is an arrow function that is defined inside the 'lol' object. Arrow functions do not bind their own 'this', therefore, the 'this' keyword inside the 'second()' method refers to the global object which is 'window' in the browser environment. Since the 'name' property is not defined on the global object, the 'console.log' statement inside the 'second()' method logs "undefined Loves himself. F Frameworks.".
The Fix: How to bind "this" to Arrow Functions
// Driver code
import './style.css';
// Start here
let lol = {
name: 'Andrew Tate',
first() {
console.log(this.name + ' Loves AngularJS');
},
second: function() {
console.log(this.name + ' Loves himself. F Frameworks.');
},
};
lol.first();
lol.second();
To fix the issue with the 'second()' method, we can define it as a regular function instead of an arrow function. By doing so, we can use the 'function' keyword to define the function and the 'this' keyword will be bound to the object that the function is a property of. Therefore, the expected output of the code snippet will be:
Andrew Tate Loves AngularJS
Andrew Tate Loves himself. F Frameworks.
If we want to keep the second() method as an arrow function, we can use a workaround to bind this to the object. One way to do this is by defining a separate variable outside the object that holds a reference to the object, and then use that variable inside the arrow function to access the object's properties. Here's an example:
// Driver code
import './style.css';
// Start here
let lol = {
name: 'Andrew Tate',
first() {
console.log(this.name + ' Loves AngularJS');
},
second: () => {
let self = lol;
console.log(self.name + ' Loves himself. F Frameworks.');
},
};
lol.first();
lol.second();
In this example, we define a variable self outside the object and assign it a reference to the lol object. Then, inside the second() method, we use self instead of this to access the name property of the lol object. This will bind this to the lol object, and the expected output will be:
Andrew Tate Loves AngularJS
Andrew Tate Loves himself. F Frameworks.
← Go home