Yes, you can add getters and setters using Object.defineProperty()
. This allows you to define custom getter and setter methods for specific properties.
Example:
const person = {};
Object.defineProperty(person, 'name', {
get() { return this._name; },
set(value) { this._name = value.toUpperCase(); }
});
person.name = 'John';
console.log(person.name); // 'JOHN'
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7459755921485434144