Javascript revealing module pattern and variables -


my question precisely same 1 javascript revealing module pattern, public properties

in thread, answer given not "why". here's same question restated own example:

myapp.user = function () {     var firstname = 'default',         lastname = 'default';      function setfirstname(name) {         firstname = name;     }      function setlastname(name) {         lastname = name;     }      function getfirstname() {         return firstname;     }      function getlastname() {         return lastname;     }      return {         getlastname: getlastname,         **getfirstname: getfirstname**,         setlastname: setlastname,         setfirstname: firstname     }; }; 

in scenario, user().getfirstname evals "default" -- if change other value via setfirstname function.

if replace setfirstname like:

 return {     getlastname: getlastname,     **getfirstname: getfirstname**,     setlastname: setlastname,     setfirstname: firstname }; 

i able access changed value. understand var firstname passed value why updated values not reflected. don't understand special function. pointer value within function living? why functions "magically" access update(s)?

where pointer value within function living?

in scope of function - contains variables has access to. access makes function closure actually.

why functions "magically" access update(s)?

because functions share variables declared in higher scope.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -