我想从私有(private)方法调用公共(public)方法,但属性“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();
});
最佳答案
如果您希望能够做到这一点,您需要像声明私有(private)函数一样声明“公共(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/ [/编辑]
另外,如果你正确使用模块模式,你可以通过使用模块名称来引用公共(public)函数,就像这样:
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();
});
但我不太喜欢这个,因为公共(public)方法可以被覆盖。
有人可以去 testModule.publicAlert = function(){EVIL CODE OF DOOM;};
并且您的内部工作将愉快地执行它。
关于javascript - 使用 javascript 模块模式时如何从私有(private)方法中调用公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4505073/