user2769810
user2769810

Reputation: 155

module reveal prototype pattern - private variables

I am using the module reveal prototype pattern (https://weblogs.asp.net/dwahlin/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern), and am having trouble accessing my this variable in my prototype functions. I have this code:

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

I am able to access this._type in _showConfirmationWindow(), but am not able to access this._type in _showWindow. The different is that the prototype is setting _showConfirmationWindow() as public and _showWindow as private, but why doesn't _showWindow get access to this._type. Why is this the case.

One solution I found is to pass this as an extra parameter in _showWindow

Upvotes: 0

Views: 64

Answers (1)

cyr_x
cyr_x

Reputation: 14257

_showWindow don't have a this reference to your instance because it's not part of ConfirmationWindow prototype because by returning only showConfirmationWindow, it never gets assigned to the prototype. You could use call to invoke your private functions like:

_showWindow.call(this, "hello")

Or adding a second argument to _showWindow like and pass the this reference when you invoke it:

_showWindow(message, self)

But i would prefer the first one.

Upvotes: 1

Related Questions