JS getters/setteres syntax


#1

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;
}


#2

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.


#3

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


#4

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.


#5

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