Use getters and setters to Control Access to an Object : ES6

Help cannot solve the challenge, please explain me what is get and set in class my concept is not clear about that. I just solve the previous challenge which was only of simple class and I’ll do it very easily. But, here I am confused about get and set attributes. Please explain me the code below.

function makeClass() {
  "use strict";
  /* Alter code below this line */
 class Thermostat{
    constructor(farenheit){
      this.farenheit = farenheit;
    }
    get temperature(){
      return 5 / 9 * (this.farenheit - 32);
    }
    set temperature(celsius){
      this.farenheit = celsius * 9.0 / 5 + 32;
    }
  }
  /* Alter code above this line */
  return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
1 Like

Oddly, I take your code, and it passes just fine. I think the issue is, you edited above and below the area you were given.

I took your code (the stuff between the)

/* Alter code below this line /

and the

/ Alter code above this line */

pasted just that into the original lesson’s space, and boom, it passes. The problem may be those two lines - the comment lines - have been edited. Each line should OPEN with a /* and CLOSE with a */. You have changed them both, removing the asterisk from one each.

I’ve just copy paste the get set portion from get hint section. Can u please explain me what is going on in code. ? I am unable to understand.

And secondly where to paste the code, is there any special portion for it ?

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

(@snowmonkey the asterisks were there, they were just being rendered as Italic)

Can u please explain me why we using get set in classes ?

Sorry about that, didn’t really answer your get/set question. Let me take a stab at it, see if this helps.

As a “big picture” thing, getters and setters are simply functions. They give us a means to store or retrieve properties on an object, but to do so without using traditional function syntax. So rather than doing

therm.setTemperature(26);

which would call a method named setTemperature we can treat it as a property:

therm.temperature = 26;

If you examine the Thermostat class, you can see that there is no property called temperature. From outside our object, it looks like there is, but internally, when the user sets or gets the temperature property, our object knows that this is, in fact, a function call.

Why go to all the bother? It lets us set an interface, making our object easier to use. The end user doesn’t have to remember odd method names like setCelciusTemperature() or 'getTempInFahrenheit()`, they simply see an interface for our object that lets them get or set the temperature, easily.

Behind the scenes, our getters and setters can do more than simply retrieve or define a value - they can do all sorts of useful behaviors. For example, in addition to the conversion that happens in Thermostat, we could define validation, not allowing invalid data to be stored.

In short, getters and setters let us define a clean, simple interface for our object. There are other ways to accomplish similar results, but these are easy to implement, both for the original developer and for the end user.

3 Likes

Thank you very much for your explained Answer. but @snowmonkey I am not getting how to get and set value. How it works. Previous challenge was of simple class in ES6 but here because of set and get code get complexed and m not getting how get and set works. And if you see my code above I am also not getting last 5 lines.

All right, let’s start with looking at the last five lines:

const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C

So the first line is simply calling makeClass(), which we’ve been told returns a Thermometer class. A class is nothing more than the blueprint of what we want our object to look like. Its not an object in itself, more of an object pattern. So that first line sets the global variable Thermostat to the returned value from makeClass() which is… the Thermostat class.

The second line uses that Thermostat class to make a new object. That object is assigned to the constant thermos, giving it all the properties and methods we’ve defined in that Thermostat class.

The third, fourth and fifth lines uses the getter and setter, so that tells us our Thermostat class will need a special method, defined slightly differently from a normal one. Where a normal method within a class might be defined like:

class Turtle{
  getXPosition(){
    // this is a method on our Turtle class.
  },
  setXPosition(){
    // another method we're defining in Turtle
  }
}

const myTurtle = new Turtle();
const x = myTurtle.getXPosition(); // we have to use a function to get the x value...
myTurtle.setXPosition(x+50)   // and then we can use that x value to use a function to set it.

getters and setters, on the other hand, look and act like a simple property, rather than a function. Simply by starting the method definition with get or set, we tell our ES6 class that these particular functions have some very unique behaviors.

class Turtle{
  constructor(x, y){
    this._xPos = x;
    this._yPos = y;
  },
  // note that the line below starts with 'get', identifying it as a getter!
  get x(){
    return this._xPos;
  }
  // and this one has the same name, but it starts with 'set'. This one is clearly a setter.
  set x(value){
    this._xPos = value;
  }
}

const myTurtle = new Turtle(0,0); // we'll start with x and y at zero
myTurtle.x = 50; // this may LOOK like we just set a property, 
                  //   but behind the scenes, we called a function!
console.log(myTurtle.x) // this one isn't assigning anything, so javascript knows to call the 'get' method

In the Thermostat, the getter and setter are called temperature. so within the Thermostat class, we’d need to have a function that starts get temperature(){ ...}, thus defining this as a getter function. We wouldn’t do therm.temperature(), as we’ve told javascript that it’s a special getter method, so we would simply let temp = therm.temperature;, and javascript knows to call that getter function.

3 Likes

Thank you Tobias for your frequent reply. what is this keyword used for ?
why we using this.farenheit = farenhiet
or
this.farenhiet = cesius.

It could be run as simple like

farenhiet = farehiet or farenhiet = celcius ??

GREAT question. in javascript, this is a keyword, and a very tricky one.

Within our object, we have a “private variable space”, usually called a “local scope”. That means that any variables inside that space are completely private, and unavailable to the outside world. We also have, within our object, properties. So we can do things like:

class Person{
  constructor(firstName, lastName, age, friends){
    /****
     * Now, in here, we have created some local variables, which were passed in as parameters.
     *    firstName, lastName, age and friends are all contained by the object, and not visible to
     *    anything outside this object. They are local, and they are, to all intents and purposes,
     *    private.
     ****/
   console.log(`Hello, my name is ${firstName} ${lastName}. Nice ta meetcha!`;
  }
}

// what would happen if we did this?
const bobDylan = new Person('Bob', 'Dylan', 74, ['Neil Young','Cass Elliot','Janis Joplin']);
console.log(/** how can I retrieve Bob Dylan's age here? **/)

Suppose, however, we wanted someone to be able to get at the name from the outside? For example, suppose we used the name as a key, to allow us to search for this particular instance of Person? How can we attach one of these variables so they’re visible from outside?

In other words, suppose we wanted to do something like those last two lines, where we get properties like bobDylan.age?

That’s where the this keyword comes in. Within the object, this refers to the object itself, so we can assign properties to it directly, without knowing which instance of our class it is - it is always this (think of a “you are here” arrow that always follows you around… cos you are here.)

So that means, in our constructor, I could:

class Person{
  constructor(firstName, lastName, age, friends){
     // Same as before, but let's use the 'this' keyword to attach the variables as attributes.
     this.name = {
       first: firstName,
       last: lastName
    }; // note that we aren't restricted to the same variable names - we can juggle it however we want
    this.age = age; // or, if we want, simply assign it as-is
  }
}

I have to admit, though, I’m curious if we could simply keep them as variables, and use getters and setters to retrieve them - thus keeping the data private, and restricting access to a true interface. Gonna have to play, when I have a result I’ll post the repl here.

EDIT: played a little, and without some funky acrobatics, variables defined within the constructor (whether as parameters or as actual declared variables) are not accessible outside of the constructor. You could do this with ‘traditional’ object notation, but it also can get very convoluted.

The simpler solution is to attach the variables to the object (using the this keyword) as properties, and use the properties in your class methods.

1 Like

@snowmonkey, thank you very much for all your clear and detailed explanations.
It really helped me understand why get/set are not properties and the role of the this keyword.

:slight_smile:

1 Like

It can be confusing at first but used properly, it’s a powerful tool. Glad I could help.

Great job paying it forward! :grin:

1 Like