我一直在研究如何不使用全局变量http://www.yuiblog.com/blog/2007/06/12/module-pattern/
我没有得到的是如何使用'this'来访问我返回的对象中的公共变量。
console.log(this.myPublicProperty);
但如果我使用:
console.log(MYAPP.myProject.myModule.myPublicProperty);
我会在日志中看到变量。
当我尝试访问该公共变量时,我得到'undefined'。 我错过了示例代码中未显示的内容吗?
谢谢!
var MYAPP = {};
MYAPP.myProject = {};
MYAPP.myProject.myModule = function () {
//"private" variables:
var myPrivateVar = "I can be accessed only from within MYAPP.myProject.myModule.";
//"private" method:
var myPrivateMethod = function () {
console.log("I can be accessed only from within MYAPP.myProject.myModule");
}
return {
myPublicProperty: "I'm accessible as MYAPP.myProject.myModule.myPublicProperty.",
myPublicMethod: function () {
console.log("I'm accessible as MYAPP.myProject.myModule.myPublicMethod.");
//Within myProject, I can access "private" vars and methods:
console.log(myPrivateVar);
console.log(myPrivateMethod());
//The native scope of myPublicMethod is myProject; we can
//access public members using "this":
console.log(this.myPublicProperty);
}
};
}(); // the parens here cause the anonymous function to execute and return
答案 0 :(得分:1)
我不喜欢使用this
和动态绑定来访问公共变量,因为如果我将我的一个函数作为回调传递,它会破坏。我更喜欢让我的模块中的引用是静态的:
var M = { //explicit name
f1: function(){ return M.f2(); },
f2: function(){ }
};
return M;