IIFE function is a function of expression, rather than the function declaration

The following code prints what, and why?

var b = 10;
(function b(){
    b = 20;
    console.log(b); 
})();

On this topic, see someone in the know almost replied:

  1. Different function expressions and function declarations, function name only valid within the function, and this binding is the binding constant.
  2. Be a constant for the assignment, an error in strict mode, the non-strict mode fail silently.
  3. IIFE function is a function of expression, rather than the function declaration.

In fact, somewhat similar to the following code, but not identical, to use const because no matter what mode will TypeError types of errors

const foo = function () {
  foo = 10;
  console.log(foo)
}
(foo)() // Uncaught TypeError: Assignment to constant variable.

A few examples:

var b = 10 ; 
( function b () {
    // internal scope, would go to look for is already declared variable b, there are 20 direct assignment, it has indeed been found that the named function function b () {. }, b do take this assignment; 
   // . IIFE function can not be assigned (internal mechanism, similar to const defined constants), so the invalid 
  // (That's "internal mechanism", trying to figure out the need to review some information , IIFE understand the mode of operation of the engine, JS, etc. stack memory IIFE manner) 
    B = 20 ; 
    the console.log (B); // [Function B] 
    the console.log (window.b); // 10, not 20 
}) ();

So strict mode can see the error:Uncaught TypeError: Assignment to constant variable

var b = 10;
(function b() {
  'use strict'
  b = 20;
  console.log(b)
})() // "Uncaught TypeError: Assignment to constant variable."

Other examples of situations:

There are window:

var B = 10 ; 
( function B () { 
    window.b = 20 is ; 
    the console.log (B); // [Function B] 
    the console.log (window.b); // 20 is inevitable 
}) ();

There are var:

var B = 10 ; 
( function B () {
     var B = 20 is; // IIFE internal variables 
    the console.log (B); // 20 is 
   the console.log (window.b); // 10 
}) ();

Guess you like

Origin www.cnblogs.com/wangxi01/p/11209060.html