To use this
keyword, you must have an instance of an object, to do so, you can create a Person
class and initialize a person
.
class Person {
constructor({ firstName, middleName }) {
this.firstName = firstName
this.middleName = middleName
}
get fullName() {
return `${this.firstName} ${this.middleName}`
}
}
const person = new Person({
firstName: 'Régis',
middleName: 'Faria',
})
console.log(person.fullName)
Otherwise, you must set firstName
and middleName
first:
const firstName = 'Régis'
const middleName = 'Faria'
const person = {
firstName,
middleName,
fullName: `${firstName} ${middleName}`
}
console.log(person.fullName);
I personally prefer to use TypeScript:
// create a Person type
type Person {
firstName: string
lastName: string
fullName: string
}
// then it's ok to have variable
const firstName = 'Régis'
const middleName = 'Faria'
// then your person
const person: Person = {
firstName,
middleName,
fullName: `${firstName} ${middleName}`
}
console.log(person.fullName)