Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

oop - How to override 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 answer as "simron" but I expect "jothika".

How my understanding is wrong?

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...