2

Hi Guys I am facing difficulty in one of scenario where in I m not able to define local function in my Manager.prototype. Please find below detail..

I have a Constructor Function Employee.

function Employee(id){
   this.id = id;
}
Employee.prototype.getID = function(){
    return this.id;
}
var mark = new Employee(123);

Again I have a Manager Constructor

function Manager(managerOf){
   this.managerOf = managerOf;
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.getManagerOf = function(){
    return this.managerOf;
}
var john = new Manager(mark);

Now I want to define a function calcSalary() which is only accessible from getManagerOf() method & not from outside. [john.calcSalary() should not work]

Gautam
  • 815
  • 6
  • 15
  • 2
    Just declare it within the scope of `getManagerOf`. It won't be accessible from outside the function. – haim770 Nov 08 '16 at 12:56
  • No I wanted it be more generic, so that tomorrow if I add one more prototype function it can be accessible from that one as well, any thoughts? – Gautam Nov 08 '16 at 13:03
  • There are patterns used to achieve "private" methods in JS. Typically using closures. And the example provided in the answer of @Daniel A. White is a good one. – haim770 Nov 08 '16 at 13:04
  • If you want your managers to inherit from employee, then you need an `Employee.call(this, id)` call in the `Manager` constructor - currently `john.getID()` wouldn't work. – Bergi Nov 08 '16 at 13:05
  • @Bergi you are absolutely right, I can do that , but right now my concern is how can we add a generic local function to a prototype which can be accessed by all protoypal functions. – Gautam Nov 08 '16 at 13:12

1 Answers1

3

You could hide it with a self executing function.

var Manager = (function() {
   function calcSalary() {}
   function Manager(managerOf){
      this.managerOf = managerOf;
   }
   Manager.prototype = Object.create(Employee.prototype);
   Manager.prototype.getManagerOf = function(){
      // call calcSalary
      return this.managerOf;
   }
   return Manager;
}());

var john = new Manager(mark);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445