Getters and Setters III


#1

Why is nothing being printed to my console? Its saying I’ve done everything right!

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

},
get age() {
console.log(${this.name} is ${this.age} years old.)
console.log(person.age)
}
};
person.age = ‘Thirty-nine’;
person.age = 39


#2

Getters and Setters are internalized constructs that have a purpose across the class instance. We want our getters to be useful to any internal call to them which means we return only the object or value described by the name of the getter.

get age() {
    return this._age;
}

We could add a method to our object that would log a representation of its data properties.

repr() {
    return `${this.name} is ${this.age} years old.`;
}

Then,

console.log(person.repr());

Of course this would imply setters for both _age and _name properties.

Keep in mind that getters and setters are methods, but they have some real horsepower.

console.log(person.age)

Looks like we are polling the age attribute of the person object. Only thing is, the person object doesn’t have an age attrbute. Likewise if we were to poll person.name. Both of the those queries are actually method calls to their respective getters.

console.log(person._name)

will work, but is uncommon. Nice of ECMA to come up with this little workaround.


#3

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