gpt4 book ai didi

javascript - 模块揭示原型(prototype)模式 - 私有(private)变量

转载 作者:行者123 更新时间:2023-12-03 04:50:55 24 4
gpt4 key购买 nike

我正在使用模块显示原型(prototype)模式( https://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern ),并且在访问原型(prototype)函数中的 this 变量时遇到问题。我有这个代码:

myapp.ConfirmationWindow = function (temptype) {
this._type = temptype;
};

myapp.ConfirmationWindow.prototype = function () {
this._showConfirmationWindow = function (message) {
var a = this._type; //valid
return _showWindow("hello");
}

this._showWindow = function (message) {
var a= this._type; //invalid
}
return {
showConfirmationWindow: _showConfirmationWindow
};
}();

我可以在 _showConfirmationWindow() 中访问 this._type,但无法在 _showWindow 中访问 this._type。不同的是,原型(prototype)将 _showConfirmationWindow() 设置为公共(public),将 _showWindow 设置为私有(private),但为什么 _showWindow 无法访问 this._type。为什么会这样。

我发现的一个解决方案是将其作为 _showWindow 中的额外参数传递

最佳答案

_showWindow 没有对您的实例的 this 引用,因为它不是 ConfirmationWindow 原型(prototype) 的一部分,因为仅返回 showConfirmationWindow ,它永远不会被分配给原型(prototype)。您可以使用 call 来调用您的私有(private)函数,例如:

_showWindow.call(this, "hello")

或者向 _showWindow 添加第二个参数,例如在调用它时传递 this 引用:

_showWindow(message, self)

但我更喜欢第一个。

关于javascript - 模块揭示原型(prototype)模式 - 私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660509/

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