Understanding Private properties

Understanding Private properties
0

#1

I completed the challenge, but I don’t understand the purpose of a private property. In the Bike constructor, why can’t I just use the public method:


this.setGear = function (val) {
gear = val;
};


and then, just delete everything else in the constructor?

Your code so far

var Car = function() {
  // this is a private variable
  var speed = 10;

  // these are public methods
  this.accelerate = function(change) {
    speed += change;
  };

  this.decelerate = function() {
    speed -= 5;
  };

  this.getSpeed = function() {
    return speed;
  };
};

var Bike = function() {

  // Only change code below this line.
  var gear = 5;
  
  this.setGear = function (val) {
    gear = val;
  };
  
  this.getGear = function () {
    return gear;
  };
};

var myCar = new Car();

var myBike = new Bike();

myBike.getGear();
myBike.setGear(3);```
**Your browser information:**

Your Browser User Agent is: ```Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36```.

**Link to the challenge:**
https://www.freecodecamp.org/challenges/make-object-properties-private

#2

Even with your example, you are still making use of the private property gear. I think the car example code makes it more clear, because there is not a way to change the speed variable other than using the accelerate and decelerate public methods. In the bike’s example, the private property gear is used as a way to create a default value of 5 for gear and then you can use the setGear method to change it if you want. The point is still there is no other way to change gear except by using the public method setGear.