javascript - What is the use of return statement inside a function? -


    var obj = {          func: function() {             return: {            add: function() {              }           }          },         somefunc: function() {       }    }  

the orginal code behind used convert this...

var hash = (function() {      var keys = {};      return {               contains: function(key) {      return keys[key] === true;               },      add: function(key) {       if (keys[key] !== true){          keys[key] = true;                   }        };  })(); 

questions:

  1. what use of return keyword?
  2. can structure this, class?

on basic level, return keyword defines function should return. if have function:

function foo() { return 4; } 

and call it:

var bar = foo(); 

foo() return 4, hence value of bar 4.

onto specific example:

in use case return used limit outside access variables inside hash variable.

any function written so:

(function() {...})(); 

is self-invoking, means runs immediately. setting value of hash self-invoking function, means code gets run can.

that function returns following:

return {              contains: function(key) {         return keys[key] === true;              },     add: function(key) {          if (keys[key] !== true){             keys[key] = true;                      }     }      }; 

this means have access both contains , add function so:

hash.contains(key); hash.add(key); 

inside hash, there variable keys not returned self-invoking function hash set to, hence cannot access key outside of hash, wouldn't work:

hash.keys //would give undefined 

it's way of structuring code can used create private variables through use of javascript closures. have @ post more information: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/

hope helps :)

jack.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -