Access private properties

Access private properties
0

#1

hello,

I learned in the last lesson about private Properties inside the function constructor.

what i don’t understand is, how can i access or use functions with methods?

when i try to create a new instance of this constructor function, i get undefined. here is what i tried:

//this is the constructor:

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 suburu = new Car();
console.log(suburu.accelerate(5)); // returns undefined 


#2

You’re using the function just fine, but it doesn’t have a return value. Try changing accelerate like this:

this.accelerate = function(change) {
    speed += change;
    return speed;
  };

#3

Hey @tomer-n,
like @PortableStick, you are using methods associated with the Car class, but those methods do not have a return value.
If you would have printed the Suburu’s object speed after the function you called, you would have seen that the speed is now 15.

I attached a link with a good example on Javascript ES6 classes:

https://googlechrome.github.io/samples/classes-es6/