//What is the output of the below?
let obj = {
name: "Trinits",
age: 30,
foo: function() {
console.log(this.age);
}
}
obj.foo();
Case 1:
-----------
The output of the given code will be 30.
In the code, obj is an object that has a property foo, which is a function that logs the age property of the this object. When the foo method is called on the obj object using the dot notation (obj.foo()), this inside the function refers to the object obj. Therefore, this.age refers to the age property of the obj object, which is 30.
So when the code is executed, it logs 30 to the console.
Case 2:
-------------
The output of the given code will be undefined.
In the code, obj is an object that has a property foo, which is a function that uses an arrow function expression to log the age property of the this object. However, arrow functions do not have their own this value, so this inside the arrow function will refer to the this value of the enclosing lexical scope (which is the global scope in this case, since the arrow function is defined inside an object literal). Since there is no age property in the global scope, undefined is logged.
On this page of the site you can watch the video online Program 15 this keyword | arrow function | lexical context | window object | current object context with a duration of hours minute second in good quality, which was uploaded by the user Trinits Technologies 12 April 2023, share the link with friends and acquaintances, this video has already been watched 68 times on youtube and it was liked by 3 viewers. Enjoy your viewing!