const obj = { name : "smit", surname : "patel", age: 24, calcAge : () => {…
- User
const obj = { name : "smit", surname : "patel", age: 24, calcAge : () => { console.log(
${this.name} age is ${this.age}) } }obj.calcAge()
- Assistant
const obj = {
name : "smit",
surname : "patel",
age: 24,
calcAge : () => {
console.log(${this.name} age is ${this.age})
}
}
obj.calcAge()
In your JavaScript code, you're defining the calcAge method as an arrow function within the obj object:
const obj = {
name: "smit",
surname: "patel",
age: 24,
calcAge: () => {
console.log(`${this.name} age is ${this.age}`)
}
}
obj.calcAge()
When you run obj.calcAge(), you might expect the output to be:
smit age is 24
However, instead of logging the expected message, it likely logs:
undefined age is undefined
The root of the issue lies in how arrow functions handle the this keyword compared to regular functions.
Arrow Functions (() => {}):
this.this, meaning they inherit this from the surrounding (parent) scope at the time they are defined.this does not refer to obj.Regular Functions (function() {} or method shorthand method() {}):
this.this refers to the object itself.To ensure that this inside calcAge refers to the obj object, define calcAge as a regular function. You can do this in two ways:
Using the function Keyword:
const obj = {
name: "smit",
surname: "patel",
age: 24,
calcAge: function() {
console.log(`${this.name} age is ${this.age}`)
}
}
obj.calcAge() // Output: smit age is 24
Using the Method Shorthand Syntax (ES6):
const obj = {
name: "smit",
surname: "patel",
age: 24,
calcAge() {
console.log(`${this.name} age is ${this.age}`)
}
}
obj.calcAge() // Output: smit age is 24
Both of these approaches ensure that this inside calcAge correctly refers to the obj object, allowing you to access name and age as intended.
When to Use Arrow Functions:
this value from the surrounding context.map, filter, forEach, etc.).Avoid Using Arrow Functions for Object Methods:
this, they're not suitable for methods that need to access the object's properties via this.Here's the corrected version of your object using the method shorthand:
const obj = {
name: "smit",
surname: "patel",
age: 24,
calcAge() {
console.log(`${this.name} age is ${this.age}`)
}
}
obj.calcAge() // Output: smit age is 24
By defining calcAge as a regular method, this correctly refers to obj, and the method behaves as expected.
Not yet included in a published release.