gpt4 book ai didi

javascript - 如何覆盖javascript中的私有(private)变量?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:38:36 26 4
gpt4 key购买 nike

// 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();

我得到的答案是“simron”,但我希望是“jothika”。

我的理解怎么错了?

感谢您的帮助。

最佳答案

首先,您的代码根本不起作用,而且是错误的。
这是有效的代码:

// 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 设置为 Indian。
最后,getLover 是一个引用 Man 而不是 Indian 的闭包。
再次声明它会将其指向正确的范围。
参见 herehere了解更多详细信息和改进您的代码。

关于javascript - 如何覆盖javascript中的私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1437712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com