Back to Browse

Program 15 this keyword | arrow function | lexical context | window object | current object context

84 views
Apr 13, 2023
2:55

//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.

Download

0 formats

No download links available.

Program 15 this keyword | arrow function | lexical context | window object | current object context | NatokHD