Stuck on Setters and Getters I


#1

Hi, I’m having some syntactical issues with some of these lessons. The lesson directly preceding this would not accept my code, I hit show solution, and it accepted… my code. I’m wondering if this is a bug or not but I’ve typed this:

let person = {
_name: ‘Lu Xun’,
_age: 137,
set age(){};
};

I’ve also tried set person.age(), person.age(){}, set age();, set age(){}; and set comeOnWhyAreYouDoingThisToMe(), all to no avail. I hit show solution and see no difference. The error I get is that there has to be a formal parameter, but the instructions say to put in an empty method. I don’t want an easy way out and I want to understand why it’s not working if possible


#2

can you share the exercise url?


#3

You have to set a variable to the ‘set age’ setter. This exercise really confused me too, I did :

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

set age(ageIn) {
if (typeof ageIn === ‘number’) {
this._age = ageIn;
}
else {
console.log(‘Invalid input’);
return ‘Invalid input’;
}
}

};


#4

I think the issue I had was that is specifically asked me to set “.age()” as empty, when putting a “.” or nothing in the parenthesis returned an error. I got past it by ignoring what the lesson specifically asked for and putting something in those parenthesis and leaving off the .

Link to lesson

It says:

Let’s consider a new person object. We want to add a setter method that changes the age of person.

Notice, we already prepended the _age property with an underscore.

Start by adding an empty .age() setter method.


#5

getters need a parameter, otherwise you get a syntax error


#6

Yeah you are right boardjumper, i was confused with the wording, I was only able to get the solution through failing and it giving me the solution. This lesson should be more clear, in explaining the use of typeof and its lesson plan.


#7

Do setters also need a parameter, always?


#8

I thought getters do not need a parameter, but setters apparently do.


#9

Without a parameter there is no new value to set the property with.

set age (newAge) {
    this._age = newAge;
}

This corresponds with the syntax used to set a new age.

const jill = new Person('Jill', 25);

jill.age = 26;

The assigned value is the argument in the call to set age().

As for getters not needing parameters, they draw upon instance variables that are visible to them via the this context object.

console.log(jill.age);

would be handled by the get age() method…

get age() {
    return this._age;
}

#10

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