13. Getters and Setters 2


#1

I’m a little confused here. for this assignment I used a setter to change the age of attribute. here’s the code:

let person = {
_name: ‘Lu Xun’,
_age: 137,
set age(newAge) {
if (typeof newAge === ‘number’){
this._age = newAge;
console.log(this._age);
}
else {
return ‘Invalid input’;
}
}
};

person.age=39;

My question is, isn’t this a function? shouldn’t I be able to use " person.age(39); " and get a solution? Someone out there educate me please.


#2

It’s a function, yes, but person.age doesn’t refer to that function so person.age() won’t call it. It gets invoked when you assign the corresponding property


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.