Ranjeet Gautam Ranjeet Gautam - 27 days ago 11
Javascript Question

How to define a local function in Constructor.prototype in Javascript

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]

Answer

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);
Comments