oop - Javascript: Assigning a Private Method to Private Variable -


so i'm having javascript issues. i'm not pro, , don't understand why not work. trying assign private variable return value of private function. if set var xxx=function name() execute function when reference xxx. here code. note - var username=getsessionuser(); below.

//namespace var sessioncontrols=sessioncontrols || {}; sessioncontrols.app=sessioncontrols.app || {};   sessioncontrols.app.user = (function () { // defined within 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 public properties     properties:{         publicproperty1: privateproperty1,         sessionname:username     },     //another nested namespace     utils:{         publicmethod2: privatemethod2     }   } })(); 

this how called in routine.

var name=sessioncontrols.app.user.properties.sessionname; alert(name);     

why doesn't work?

you've got simple ordering problem:

var username=getsessionuser();  //privatemethod var getsessionuser=function(){var mname='my name'; return mname;}   

javascript won't complain undefined variable reference, because treats var statements in function if appeared @ start of code. however, initializations in var statements carried out in sequence appear.

thus, @ point code attempts initialize username, variable getsessionuser not defined.

if re-order 2 statements function defined first, part @ least work.

alternatively, define function function declaration statement:

function getsessionuser() {   var mname = "my name";   return mname; } 

then code work if leave initialization of username before function, because function declarations "hoisted" implicitly start of function.


Comments

Popular posts from this blog

SQL php on different pages to Insert (mysqli) -

How to combine associative arrays in bash? -

c++ - No viable overloaded operator for references a map -