Hello. Today I was working with React when I bumped into an error I’ve never seen before: TypeError: (void 0) is undefined. That said, I realized I’ve tried something I’ve never tried before; namely:
let obj = {
name: 'John',
surname: 'Doe',
fullName: this.name + this.surname
}
//TypeError: (void 0) is undefined
I realize this is a very naive code: since it’s an object literal, I already know the values of name and surname. But I’d like to understand why, technically, it does not work. What is the difference between the above code and the other options we normally use?
let obj = {
name: 'John',
surname: 'Doe',
fullName: () => this.name + this.surname
}
//OR
let obj = new function(){
this.name = 'John'
this.surname = 'Doe',
this.fullName = this.name + ' ' + this.surname
}
console.log(obj.fullName) //John Doe
Is it because in the first example, when we write the fullName property we’re trying to retrieve it from an object that does not exist yet? If so, in the example where the fullName is computed through a function, how does the function have access to the properties? Is it triggered only after the object is initialized?
I hope this question is not to silly, I’m really curious to understand this point… thanks in advance for you answers!