JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)
What is the difference between get and defineProperty
Both have similar results unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.
Practical Code Example
javascript
// 1. Using getter in object literal syntax:
const user = {
first: 'John',
last: 'Doe',
get fullName() { return `${this.first} ${this.last}`; }
};
console.log(user.fullName); // 'John Doe'
// 2. Using Object.defineProperty (allows setting enumerable, configurable):
Object.defineProperty(user, 'greeting', {
get() { return `Hello, ${this.fullName}`; },
enumerable: false
});
console.log(user.greeting); // 'Hello, John Doe'