简体   繁体   中英

Cannot Understand this JavaScript Construct

Below I have attached an excerpt from the chapter 10 of Eloquent JavaScript book.

var dayName = function () {
    var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"
    ];
    return function (number) {
        return names[number];
    };
}(); //==> '();' this construct right here....

console.log(dayName(3));

What I cannot understand is why this function has a trailing (); ?

What is it's use? I have tried finding the answer but I don't know what to look for.

Can anybody explain me why this construct is added in the end? Any help would be invaluable.

Call the function immediately and assign the returned value to the variable.

var name = function() {
    // Function body
}();

In your case, the function returns another function. Thus, the function dayName is the returned function having access to the names variable.

The inner function is closure and thus have access to the outer function variables.

In other words, the function is

var dayName = function (number) {
    return names[number];
};

with having access to the private variable names .

Also see

  1. What is the (function() { } )() construct in JavaScript?
  2. How do JavaScript closures work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM