What are __defineGetter__() and __defineSetter__() functions?

Viewed 17442

What are __defineGetter__() and __defineSetter__() functions in prototype of every Object?

3 Answers

.__defineGetter__ it means when you refer to object.[param1] a function is executed. .__defineSetter__ it means when you set object.[param1] a function is executed. for example, like this:

const person = {
  firstName: 'john',
  lastName: 'doe',
};

person.__defineGetter__('fullName', () => `${person.firstName} ${person.lastName}`);
person.__defineSetter__('fullName', v => {
  person.firstName = v.split(' ')[0];
  person.lastName = v.split(' ')[1];
});

or if you want cls to clear the console,

this.__defineGetter__('cls', console.clear);
Related