Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override private variable in javascript?

Tags:

javascript

oop

// 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.

like image 561
rajakvk Avatar asked Jan 29 '26 14:01

rajakvk


2 Answers

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.

like image 160
the_drow Avatar answered Jan 31 '26 04:01

the_drow


The getLover property on the instance refers to the closure you defined within the Man constructor. The lover local variable inside Man is the one in-scope for that function. The lover variable you declared inside Indian has nothing whatsoever to do with the one declared inside Man, no more than local variables declared inside other functions do.

For Indian to manipulate the private lover variable inside Man, you would have to give Indian some access to it via an accessor function -- but then everything would be able to change it via that same accessor function.

like image 22
T.J. Crowder Avatar answered Jan 31 '26 03:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!