在使用javascript模块模式时,如何从私有方法中调用公共方法?

Ota*_*Ota 9 javascript module-pattern

我想从私有方法调用公共方法,但属性"this"指向窗口对象.

请注意我正在尝试应用模块模式.您可以在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();
});
Run Code Online (Sandbox Code Playgroud)

dav*_*vid 11

如果您希望能够这样做,您需要像私有函数一样声明'public'函数,然后将其公开为public.像这样:

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

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

        var publicAlert = function(){
            alert("publicAlert");            
        };

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

            publicAlert: publicAlert
        };
    });

    mp = new modulePattern($);
    mp.publicMethod();
});
Run Code Online (Sandbox Code Playgroud)

[编辑]我也鼓励你养成点击jsfiddle顶部的'jslint'按钮的习惯,你的代码缺少几个分号,你还重新声明了你的appendText函数中的'text'变量(它已经通过了)

此外,您使用的模块模式与我学习它的方式略有不同.您是否有指向参考资料的链接?

这就是我所知道的模块模式:http://jsfiddle.net/sVxvz/ [/ Edit]

此外,如果正确使用模块模式,则可以使用模块名称来引用公共函数,如下所示:

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

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

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

$(function() {
    testModule.publicMethod();
});
Run Code Online (Sandbox Code Playgroud)

但我真的不喜欢这个,因为公共方法可以被覆盖.有人可以去testModule.publicAlert = function(){EVIL CODE OF DOOM;};,你的内部工作将愉快地执行它.