How to override a private variable in javascript?

// 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 the answer as "simron", but I expect "jothika".

How is my understanding wrong?

Thanks for any help.

+3
source share
3 answers

First of all, your code doesn't work at all, and this is wrong.
Here is 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 , .
ctor .
, , getLover - , , .
.
. .

+4

getLover , Man. lover Man , . lover, Indian, Man, , , .

Indian, lover Man, Indian , .

+2

My advice: get rid of all this expensive shit method and don't try to translate concepts from one language to another.

For performance reasons, methods should be in the prototype. Otherwise, a new function object must be created for each instance (which forms a closure by the local vaiables of the constructor), which is extremely inefficient.

If you want to hide properties (i.e. 'private' fields), add a type prefix to their name _private_and tell the programmer not to do stupid things.

+1
source

All Articles