Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

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

    var obj = {

        func: function() {    
        return: {
           add: function() {
             }
          } 
        },
        somefunc: function() {
      }
   } 

The orginal code behind where i used to 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 is the use of return keyword?
  2. Can i structure like this, my class?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On the most basic level, the return keyword defines what a function should return. So if I have this function:

function foo() { return 4; }

And then call it:

var bar = foo();

foo() will return 4, hence now the value of bar is also 4.

Onto your specific example:

In this use case the return is used to basically limit outside access to variables inside the hash variable.

Any function written like so:

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

Is self-invoking, which means it runs immediately. By setting the value of hash to a self-invoking function, it means that code gets run as soon as it can.

That function then returns the following:

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

This means we have access to both the contains and add function like so:

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

Inside hash, there is also a variable keys but this is not returned by the self-invoking function that hash is set to, hence we cannot access key outside of hash, so this wouldn't work:

hash.keys //would give undefined

It's essentially a way of structuring code that can be used to create private variables through the use of JavaScript closures. Have a look at this post for more information: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/

Hope this Helps :)

Jack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...