Sometimes, we want to add an alias for an object property in JavaScript.
In this article, we’ll look at how to add an alias for an object property in JavaScript.
How to add an alias for an object property in JavaScript?
To add an alias for an object property in JavaScript, we can add a getter.
For instance, we write:
const obj = {
a: 1,
get b() {
return this.a
}
}
console.log(obj.a)
console.log(obj.b)
obj.a = 2
console.log(obj.a)
console.log(obj.b)
to add the b
getter which returns the latest value of a
.
Therefore, from the first 2 console logs, we see that obj.a
and obj.b
are both 1.
Then after we set obj.a
to 2, we see that obj.a
and obj.b
from the console log.
Conclusion
To add an alias for an object property in JavaScript, we can add a getter.