search

Home  >  Q&A  >  body text

javascript - 小白学js遇到的一个疑惑

学习js看到这么一段话:

如果在严格模式下,函数只能在顶层作用域和函数内声明,其他情况(比如if代码块、循环代码块)的声明都会报错。
然后我写了如下代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<code><script type="text/javascript">

    "use strict";

    if(true){

      function f1(){

        console.log('f1');

      }

      f1();

    }

    if(true){

      var f2;

      f2 = function(){

        console.log('f2');

      }

      f2();

    }

    if(true){

      let f3;

      f3 = function(){

        console.log('f3');

      }

      f3();

    }

 </script></code>

我按那段话说的做了,可是没有报错啊,chrome运行是正常结果啊,这是为什么呢?

巴扎黑巴扎黑2894 days ago298

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-10 17:18:23

    严格模式只允许在全局作用域或函数作用域的顶层声明函数,你所举的三个例子,都是属于在函数作用域的顶层声明的。
    如果变成这样就会报错了:

    1

    2

    3

    4

    5

    6

    7

    8

    <code>"use strict";

    if(true){

      function f1(){

        console.log('f1');

      }

    }

    f1();

    </code>

    reply
    0
  • Cancelreply