Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript Getters and Setters Setters

Samuel Kleos
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 12,719 Points

What's the purpose of the underscore if you can just different words for getting and setting?

Here is the alternative without using the getter method to get some other hidden underscore value, where the property value is set directly in the setter method.

class Pet {
    constructor(animal, age, breed, sound) {
        this.animal = animal;
        this.age = age;
        this.breed = breed;
        this.sound = sound;
    }

    set setOwner(owner) {
        this.owner = owner;
        console.log(`setter method called`);
    }

    speak() {
        console.log(this.sound);
    }
}

const casper = new Pet('cat', 10, 'ABYSSINIAN', "meowmeowmeow");
const ernie = new Pet('dog', 10, 'pug', "Woof!");

ernie.setOwner = 'Ashley';
console.log(ernie);
console.log(ernie.owner);
treehouse:~/workspace$ node pet.js                                                                                        
setter method called                                                                                                      
Pet {                                                                                                                     
  animal: 'dog',                                                                                                          
  age: 10,                                                                                                                
  breed: 'pug',                                                                                                           
  sound: 'Woof!',                                                                                                         
  owner: 'Ashley' }                                                                                                       
Ashley                  

1 Answer

Steven Parker
Steven Parker
229,785 Points

Backing store names are not required to begin with an underscore, but it is a commonly used convention to make it clear what the developer's intention for the variable is.