I've been looking at how to not use Global Variables http://www.yuiblog.com/blog/2007/06/12/module-pattern/
What I'm not getting is how to use 'this' to access a public variable within my returned object.
console.log(this.myPublicProperty);
But if I use:
console.log(MYAPP.myProject.myModule.myPublicProperty);
I'll see the variable in the log.
I get 'undefined' when I try and access that public variable. Am I missing something that's not shown in the example code?
Thanks!
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
myPublicMethodismyProject: No, it'sMYAPP.myProject.myModule, if you can even say this. It depends on howmyPublicMethodis called.console.log(myPrivateMethod())logsundefinedbecause themyPrivateMethodlogs something and then implicitly returnsundefined(because it does not return anything). So that log will evaluate toconsole.log(undefined). The lastconsole.logwiththis.myPublicPropertyhas no problems; at least I cannot reproduce any issues withthis.