Blocking in JavaScript and internal functions

I'm trying to figure it out. In my opinion, ES5 does not have the ability to block the scope, so the internal function f () should be within the framework of the body test.

These are the results of running the function.

  • test (true); // ["local", "local"]
  • test (false) // f not defined

However, I cannot understand why test (false) gives an error? I was expecting - [local].

  function f() { return "global"; }

    function test(x) {
        var result = [];
        if (x) {
            function f() { return "local"; } // block-local

            result.push(f());
        }
        result.push(f());
        return result;
    }
+4
source share
2 answers

Here's what your code looks like when compiling:

function f() { return "global"; }

    function test(x) {
        var result = [];
        var f; 
        if (x) {
            f = function () { return "local"; } // block-local

            result.push(f());
        }
        result.push(f());
        return result;
    }

A variable f(a variable containing a pointer to a function) is declared at the top of the function, but is defined in a conditional expression.

JavaScript , . , , , . f.

:

function f() { return "global"; }

    function test(x) {
    "use strict" // STRICT MODE TAG INSERTED HERE
        var result = [];
        if (x) {
            function f() { return "local"; } // block-local

            result.push(f());
        }
        result.push(f());
        return result;
    }

test(true);
test(false);

:

["local","global"] //test(true);

["global"] //test(false);

, f , .

+3

, , 'f' , f.

x , "f" , "f", f

, window.f(), f() if IIFE

function f() {
  return "global";
}

function test(x) {

  var result = [];
  if (x) {

    // block-local
    result.push((function f() {
      return "local";
    })());
  }
  result.push(f());
  return result;
}
var res = test(true);
console.log(res);
var res1 = test(false);
console.log(res1);

,

0

Source: https://habr.com/ru/post/1663770/


All Articles