How can i call a public method from within a private one when using the javascript Module Pattern?

I would like to call a public method from a private one but the property "this" refers to the window object.

Please note i am trying to apply the module pattern. You can find a working code example at jsfiddle.net

// how can i access a public method from a private one?
// (in this example publicAlert from privateMethod)
// this refers to the window object.

$(function() {
var modulePattern = (function($)
{
    var privateMethod = function()
    {
        appendText("called privateMethod()");
        this.publicAlert();
    };

    var appendText = function(texToAppend)
    {
        var text = $('#output').text() + " | " + texToAppend;
        $('#output').text(text);
    };

    return {
        publicMethod : function()
        {
            appendText("called publicMethod()");
            privateMethod();
        },

        publicAlert : function()
        {
            alert("publicAlert");
        }
    };
});

mp = new modulePattern($);
mp.publicMethod();
});

9
задан Ota 21 December 2010 в 14:23
поделиться