简体   繁体   中英

What is purpose of setting IIEF to a variable if it doesn't return an inner function?

I understand the point when a function returns another function:

let foo = (function() {
     let num = 10;
     return function(x) {
         return num + x
     }
})();

foo(10) // 20

but I've also seen the following and I don't quite understand it. Wouldn't this just execute immediately and the variable would have no use?

let foo = (function() {
    return "Testing"
})();

If all you do inside the function is return a string, in your example, yes, there wouldn't really be any point, it's just confusing overhead.

An IIFE is useful to control the scope of an operation. I could imagine returning a string (or some other non-function primitive) at the end of a not-entirely-trivial process as arguably reasonable, for example:

 const userHasPermissions = (() => { // lots of lines of logic here checking various things // return depending on the logic carried out return true; })();

Well yes, the second example is exactly the same as:

let foo = "Testing";

so the IIFE is pretty useless.

The correct term is IIFE (Immediately Invoked Function Expression) - And as per you said, those sample don't really give good explanation why it was used.

This is all about variable scoping as all variables defined in the scope of this IIFE is only accessible within it only, so you don't have to worry of name any variable conflicting those that are in global scope.

Consider the following code;

(function () {
  var status= 'Fetched';
  window.$$status = 'Foo';

  console.log(status); // 'Fetched'
  console.log(window.$$status); // "Foo"
})();

console.log(status); // undefined
console.log(window.$$status); // 'Foo'.
console.log(window.status); // '' .

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