简体   繁体   中英

Javascript: Assigning a Private Method to Private Variable

So I'm having some JavaScript issues. I'm not a pro, and don't understand why this does not work. All I am trying to do is assign my private variable to the return value of a private function. If I set var xxx=function name() will it execute the function when I reference xxx. Here is my code. Note - var username=getsessionuser(); below.

//Namespace
var SESSIONCONTROLS=SESSIONCONTROLS || {};
SESSIONCONTROLS.APP=SESSIONCONTROLS.APP || {};


SESSIONCONTROLS.APP.User = (function () {
// defined within the local scope

//Private Variable
var username=getsessionuser();

//Privatemethod
var getsessionuser=function(){var mname='My Name'; return mname;}  

//Private Property & Method Example
var privateMethod1 = function () { alert("private method 1"); }
var privateMethod2 = function () { alert("private method 2");}

var privateProperty1 = 'foobar';
return {        
    //Public Method & Nested Namespace examples
    //Public Methods
    publicMethod1: privateMethod1,
    //nested namespace with public properties
    properties:{
        publicProperty1: privateProperty1,
        sessionname:username
    },
    //another nested namespace
    utils:{
        publicMethod2: privateMethod2
    }
  }
})();

This is how its called in another routine.

var name=SESSIONCONTROLS.APP.User.properties.sessionname;
alert(name);    

Why doesn't this work?

You've got a simple ordering problem:

var username=getsessionuser();

//Privatemethod
var getsessionuser=function(){var mname='My Name'; return mname;}  

JavaScript won't complain about an undefined variable reference, because it treats all the var statements in a function as if they appeared at the very start of the code. However, the initializations in var statements are carried out in the sequence they appear.

Thus, at the point your code attempts to initialize username , the variable getsessionuser is not defined.

If you simply re-order those two statements so that the function is defined first, then that part at least will work.

Alternatively, you could define the function with a function declaration statement:

function getsessionuser() {
  var mname = "My Name";
  return mname;
}

Then your code will work even if you leave the initialization of username before the function, because function declarations are also "hoisted" up implicitly to the start of the function.

You are calling getsessionuser() before it is defined. Move

var getsessionuser=function(){var mname='My Name'; return mname;} 

above

var username=getsessionuser();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM