Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this keyword to access public variable in Javascript Module Pattern

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
like image 372
kaplan Avatar asked Dec 06 '25 20:12

kaplan


1 Answers

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;
like image 117
hugomg Avatar answered Dec 09 '25 08:12

hugomg