[英]module reveal prototype pattern - private variables
我正在使用模塊顯示原型模式( https://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern ),並且無法訪問我的這個變量在我的原型函數中。 我有以下代碼:
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。 不同之處在於原型將_showConfirmationWindow()設置為public,將_showWindow設置為private,但是_showWindow為什么無法訪問this._type。 為什么會這樣呢?
我發現的一種解決方案是將其作為_showWindow中的額外參數傳遞
_showWindow
沒有對您的實例的this
引用,因為它不是ConfirmationWindow prototype
的一部分,因為僅返回showConfirmationWindow
,就永遠不會將其分配給原型。 您可以使用call
來調用您的私有函數,例如:
_showWindow.call(this, "hello")
或向_showWindow
添加第二個參數,並在調用它時傳遞this
引用:
_showWindow(message, self)
但是我更喜歡第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.