JS getters/setteres syntax


In the sample code below what is the relation between “age” and “_age”? Can we use “set _age” instead?

let person = {
_name: ‘Lu Xun’,
_age: 137,

set age(ageIn) {
if (typeof ageIn === ‘number’) {
this._age = ageIn;


age is the instance method, _age is the instance data.

No. We would never use an underscore in an instance property reference.

person.age = 138;     //  right

person._age = 138;    //  wrong

Pay particular note to the fact that set age is NOT a function. It is a setter that receives the parameter in the form of an assignment, as above.


thank you for your reply :slight_smile:
can I use
set _myAge(ageIn){}
instead of
set _age(ageIn){}
and secondly:
person._age = 138; // you said is wrong
trigger an error?


You will need to refer to the specs for an exact answer. As I understand it, the underscore has special meaning in connecting a setter to a property. It is not something we can trifle with, but need to appreciate that relationship.


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