I'm learning about javascript using various books and I'm noticing that I can't find an adequate explanation of when, exactly, you use return. I understand that you use it when you want to return a value from a function, but then there's examples such as this from Javascript: The Good Parts:
var quo = function(status) {
return {
get_status: function() {
return status;
}
};
};
var myQuo = quo("amazed");
document.writeln(myQuo.get_status());
Why does status have to be returned when it is already available to the quo function as an argument? In other words, why does simply
return {
get_status: status;
}
not work?
Another example on the page immediately following:
var add_the_handlers = function(nodes) {
var helper = function(i) {
return function(e) {
alert(i);
};
};
var i;
for (i = 0; i<nodes.length; i+=1) {
nodes[i].onclick = helper(i);
}
};
Why are we returning alert(i) within a function instead of simply putting alert(i)?
function(){ alert() }andalert()aren't the same thing. Also, if you made itget_status: statusso now it's a property and not a method (somyQuo.get_statusinstead ofmyQuo.get_status()) and also is read-only instead of being modifiable.alert(I), you're returning a function that callsalert.