How To Override Private Variable In Javascript?
Solution 1:
First of all your code doesn't work at all and it's wrong. Here's the code that works:
// base functionfunctionMan(name) {
// private propertyvar lover = "simron";
// public propertythis.wife = "rocy";
// privileged methodthis.getLover = function(){return lover};
// public methodMan.prototype.getWife = function(){returnthis.wife;};
}
// child functionfunctionIndian(){
var lover = "jothika";
this.wife = "kamala";
this.getLover = function(){return lover};
}
Indian.prototype = newMan();
Indian.prototype.constructor = Indian;
var oneIndian = newIndian();
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.
Solution 2:
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.
Solution 3:
My advice: get rid of this whole priviledged method crap and don't try to shoehorn concepts from one language into another.
For performance reasons, methods should reside in the prototype. Otherwise, a new function object (which forms a closure over the constructor's local vaiables) has to be created for each instance, which is highly inefficient.
If you want to hide properties (ie 'private' fields), add a prefix like _private_
to their name and tell the programmer not to do stupid things.
Post a Comment for "How To Override Private Variable In Javascript?"