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
I don't like using this and dynamic binding to access a public variable, since it can break if I pass one of my functions as a callback or something like that. I prefer to have the references in my modules be static:
var M = { //explicit name
f1: function(){ return M.f2(); },
f2: function(){ }
};
return M;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With