9

我想从私有方法调用公共方法,但属性“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();
});
4

2 回答 2

11

如果您希望能够做到这一点,您需要像声明私有函数一样声明“公共”函数,然后将其公开。像这样:

$(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;};,你的内部工作会很高兴地执行它。

于 2010-12-22T00:06:19.483 回答
0

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

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

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

叉子:

http://jsfiddle.net/FNjJq/

于 2010-12-22T00:11:05.603 回答