How to override private variable in javascript?

javascript, oop

Solution

First of all your code doesn't work at all and it's wrong. Here's the code that works:

// base function
function Man(name) {
  // private property
  var lover = "simron";
  // public property
  this.wife = "rocy";
  // privileged method
  this.getLover = function(){return lover};
  // public method
  Man.prototype.getWife = function(){return this.wife;};
}

// child function
function Indian(){
  var lover = "jothika"; 
  this.wife = "kamala";
  this.getLover = function(){return lover};
}

Indian.prototype = new Man();
Indian.prototype.constructor = Indian;

var oneIndian = new Indian();
document.write(oneIndian.getLover());

aMan didn't exist until you declared it. Also you should have set the ctor to Indian. And at last, getLover is a closure that refers to Man and not to Indian. Declaring it again refers it to the right scope. See here and here for further details and improvements of your code.

Problem

``` // base function function Man(name) { // private property var lover = "simron"; // public property this.wife = "rocy"; // privileged method this.getLover = function(){return lover}; // public method Man.prototype.getWife = function(){return this.wife;}; } // child function function Indian(){ var lover = "jothika"; this.wife = "kamala"; } Indian.prototype = aMan; var aMan = new Man("raja"); oneIndian = new Indian(); oneIndian.getLover(); ``` I got answer as "simron" but I expect "jothika". How my understanding is wrong? Thanks for any help.

Original source

Related problems