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:
- What is the use of return keyword?
- Can i structure like this, my class?
On the most basic level, the
returnkeyword defines what a function should return. So if I have this function:And then call it:
foo()will return4, hence now the value ofbaris also4.Onto your specific example:
In this use case the
returnis used to basically limit outside access to variables inside thehashvariable.Any function written like so:
Is self-invoking, which means it runs immediately. By setting the value of
hashto a self-invoking function, it means that code gets run as soon as it can.That function then returns the following:
This means we have access to both the
containsandaddfunction like so:Inside
hash, there is also a variablekeysbut this is not returned by the self-invoking function thathashis set to, hence we cannot accesskeyoutside ofhash, so this wouldn’t work: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.