Getters and Setters I


#1

I have been following the lesson pretty well so far but this section is terrible at explaining what to do or how to do it i guess. I cant even get past step1.

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

};


#2

In ES6 method syntax is written without a function keyword…

method () {

}

set and get are special methods associated with object attributes that need getters or setters. We denote those attributes by giving their name a slight variation (prefix character) to keep them separate from the method name.

_age: 137,
get age () {
    return this._age;
}
set age (newAge) {
    this._age = newAge;
}

If all we ever need to do is retrieve an attribute, then we only need a getter, but if we wish to be able to set a new value for an attribute, then we need both a getter and a setter for that attribute.

person.age = 138

only works if there is a getter present, else it will fail, or simply add the attribute to the object, meaning it will have both, _age and age attributes. Play around with this and see what happens.

To get the person’s age,

console.log(person.age)

JS looks for a setter method if the attribute does not exist (which it doesn’t). The getter retrieves the actual attribute and returns its value.

When we write,

person.age = 138

JS looks for the attribute, like before, and turns to the getter. There being an assignment, the getter automatically invokes the setter with the value passed in to the parameter.


#3

I still don’t understand how to get past step 1. Im looking at the example and have tried everything.

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

I have even looked at the solution to try and go back to complete step 1 and still cant pass it.


#4
set age () {

}

The above code won’t work, yet, but it is a skeleton of the setter. The next steps will fill it out with parameter, possible conditional (check that the parameter is a number), and the assignment.


#5

I have this but this shows wrong.

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

}
};


#6

Please post a link to the exercise so we may investigate further. Thanks.


#7

https://www.codecademy.com/courses/learn-javascript-objects/lessons/objects/exercises/getters-setters?action=resume_content_item&course_redirect=introduction-to-javascript


#8

When i hit refresh with the code below. It says I passed 1 and 2.

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

}
};


#9

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