繁体   English   中英

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

[英]How can i call a public method from within a private one when using the 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();
});

如果您希望能够这样做,您需要像私有函数一样声明'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();
});

[编辑]我也鼓励你养成点击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();
});

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

我知道这与模块模式略有不同,但我认为它仍然提供了封装相同的好处。 公共方法声明为:

this.methodName = function(){...}

变量$ this被分配给当前实例(this),因此您可以在私有(或公共)方法中使用它来访问该实例上的任何方法或属性。

叉子:

http://jsfiddle.net/FNjJq/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM