0

i am having issues figuring this out. the instruction is as follows: We can also create private properties and private methods, which aren't accessible from outside the object.

To do this, we omit the word this from the property or method declaration.

See if you can keep myBike.speed and myBike.addUnit private, while making myBike.getSpeed publicly accessible.

here is the code:

var Car = function() {
  this.gear = 1;
  function addStyle(styleMe){
    return 'The Current Gear Is: ' + styleMe;
  }
  this.getGear = function() {
    return addStyle(this.gear);
  };
};

var Bike = function() {
  // Only change code below this line.
  this.speed = 100; //how do i change this method to be private?
  function addUnit(value) {
    return value + "KM/H"; //and this method too.
  }

  getSpeed = function () {
    return addUnit(speed); //this method is supposed to remain public.
  };

};

// Only change code above this line.
var myCar = new Car();
var myBike = new Bike();

if(myBike.hasOwnProperty('getSpeed')){(function() {return JSON.stringify(myBike.getSpeed());})();};
Mobi Blunt
  • 11
  • 1
  • 1
    Take a look at: https://carldanley.com/js-revealing-module-pattern/ or http://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript – Valentin S. Oct 28 '15 at 14:44

1 Answers1

0

Turn getSpeed into a 'privileged' function by adding this to it, so now it should be able to access private variables and methods yet be called like a public method. I have also flipped speed to a private variable by adding var to the beginning. I have changed your comments to reflect what they are:

var Car = function() {
  this.gear = 1;
  function addStyle(styleMe){
    return 'The Current Gear Is: ' + styleMe;
  }
  this.getGear = function() {
    return addStyle(this.gear);
  };
};

var Bike = function() {
  // Only change code below this line.
  var speed = 100; //now private
  function addUnit(value) {
    return value + "KM/H"; // already private
  }

  this.getSpeed = function () {this is publically callable.
    return addUnit(speed); //this is calling a private method.
  };

};

// Only change code above this line.
var myCar = new Car();
var myBike = new Bike();

if(myBike.hasOwnProperty('getSpeed')){(function() {return JSON.stringify(myBike.getSpeed());})();};

Source : http://javascript.crockford.com/private.html

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Paul Stanley
  • 4,018
  • 6
  • 35
  • 56