Why is 'set' needed? Why can't a normal method be made in place of it? SETTER


#1

Hi,

I’m on ‘Getters and Setters I’ in Intro to Javascript in the Objects part.

On the part where a person object is defined with name and age properties and the setter is used to change the age when called from outside the object.

Why is the set property needed?

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']);

Why does it not work when I put the following function as a method instead of the setter in the person object?

 age(newAge) {
    if (typeof newAge === 'number'){
      this._age= newAge;
    } else {
      console.log('Invalid input');
    }
  } 
}

Thanks!

Stu


#2

set is wired in such a way as to facilitate the syntax,

person.age = 22

however, it will not work without a corresponding get.

get age() {
    return this._age;
}

That would be non-standard and logically imperfect.


#3

Ah yes of course. person.age=22 would be setting the value of age to 22 not passing the paramater of newAge=22 to the age function.

Thats where I was going wrong. Am I right in saying that?

Stu


#4

So long as you understand how the getter and setter contribute to the object mechanics. We need the getter since it is what invokes the setter.

console.log(person.age)    // 22

person.age = 23

The setting line calls the getter, first, just as the logging line above does. Given there is an assignment, the getter invokes the setter and passes the value into its parameter.


#5

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