I'm working on a Codecademy course and have written the following code that works:
let person = {
_name: 'Lu Xun',
_age: 137,
set age (newAge) {
if (typeof newAge === 'number'){
this._age= newAge;
} else {
console.log('Invalid input');
}
}
}
person.age= 22;
console.log(person['_age']);
I was getting my head around how the set works and thought that it essentially worked the same as defining a method within the person object just with different syntax.
So I tried it out, called the age method passing 22 to it from outside the object using the normal way you would call a method. It worked the same. See below.
let person = {
_name: 'Lu Xun',
_age: 137,
age: function (newAge) {
if (typeof newAge === 'number'){
this._age= newAge;
} else {
console.log('Invalid input');
}
}
}
person.age(22);
console.log(person['_age']);
What are the benefits of using the 'set' syntax? ie why use it when a normal function/method definition works in the same way?