when read some javascript source, I found below code:
var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();
is it more effective or other reasons by returning another function?
why not use:
function fullname(name){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return shorts[name] || name;
}
This is equivalent to
… in what it does. But
… ensures that the hash/object
shorts, is * private only to the functionfullname*.
So to answer yor question, Why not
Here’
shortsis hidden insidefullname, but as Dogbert points out, it’s slowerbecause the hash
shortsis being created at each invocation.But this gives the best of both worlds:
shortsremains private tofullnameand at the same time,
shortsis only instantiated once, so performance willbe good as well.
This is what they call an IIFE (Immediately Invoked function expression). The idea is
create a function
Ainside a functionBand declare variables of use to functionAwithin function
B;s scope so that only functionAcan see them.As you can see, that’s the same as
In functionality, this is exactly the same as
I don’t see any other use.So it’s just a way of keeping variables private, and at the same time,
not loosing performance.
(see What is the (function() { } )() construct in JavaScript?)