模块揭示原型模式 - 私有变量

时间:2017-03-07 23:49:31

标签: javascript

我正在使用模块显示原型模式(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

中的额外参数传递

1 个答案:

答案 0 :(得分:1)

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

_showWindow.call(this, "hello")

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

_showWindow(message, self)

但我更喜欢第一个。

相关问题