Skip to content

Latest commit

 

History

History
21 lines (15 loc) · 808 Bytes

can_i_add_getters_and_setters_using_defineproperty_method.md

File metadata and controls

21 lines (15 loc) · 808 Bytes

Can I add getters and setters using defineProperty method?

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