我可以在私人方式中调用公共方法:
var myObject = function() {
var p = 'private var';
function private_method1() {
// can I call public method "public_method1" from this(private_method1) one and if yes HOW?
}
return {
public_method1: function() {
// do stuff here
}
};
} ();
Run Code Online (Sandbox Code Playgroud) 如何从JavaScript模块模式中的私有函数中调用公共函数?
例如,在以下代码中,
var myModule = (function() {
var private1 = function(){
// How to call public1() here?
// this.public1() won't work
}
return {
public1: function(){ /* do something */}
}
})();
Run Code Online (Sandbox Code Playgroud)
虽然这些解决方案有效,但从OOP的角度来看,它们并不令人满意.为了说明我的意思,让我们用这些解决方案中的每个解决方案对雪人进行具体实现,并将它们与简单的对象文字进行比较.
雪人1:保存对返回对象的引用
var snowman1 = (function(){
var _sayHello = function(){
console.log("Hello, my name is " + public.name());
};
var public = {
name: function(){ return "Olaf"},
greet: function(){
_sayHello();
}
};
return public;
})()
Run Code Online (Sandbox Code Playgroud)
雪人2:保存对公共功能的引用
var snowman2 …Run Code Online (Sandbox Code Playgroud)