关于 "立即执行函数" 和 "函数默认参数有函数" 的题目

114 阅读2分钟

1

(function add() {
  add = 100;          //此行代码作废,无效,因为此行代码的意思是要修改函数名,此处是立即执行函数,不允许被修改!
  console.log(add);
})();

2

(function () {
  a = 100;                   // 此时的a成为全局变量,挂在到window上!
  console.log('this', this)  //window 因为匿名执行函数默认window
  console.log(a);             // 100
})();
console.log(a);                 //100

3

(function a() {
  a = 100;                   // 失效 因为这个相当于是想改立即执行函数的函数名名 
  console.log(a);             // 函数
})();
console.log(a);                 // a is not defined

4

var a = 200;
(function () {
  var a = 100;                   
  console.log(a);             // 100
})();
console.log(a);                 //200

5

var a = 1;
function add(a = 1, b = function () {
  a = 3;
  console.log(a);                 //3  修改的是参数体内的a! 为什么没有把a=1给改了
}) {
  b();
  console.log(a);   //1 变量声明提升之后,被同名函数a覆盖,后又被同名参数a覆盖,最终值为1
  var a = 10;                                   // 赋值留在了原地,
  console.log(a);                                //10。    
  function a(){} 
}
add();
console.log(a)                              //1  最外层的a变量

6

var a = 1;
function add(a = 1, b = function () {
  a = 3;
  console.log(a);                        //3 跟着这个作用域走
}) {
  b();
  console.log(a);                     //3
}
add();
console.log(a)                         //1

7

(function add(a = 1, b = function () {
  a = 2
  console.log('b内部', a)//2 函数b里面的a是整个形参作用域的
}) {
  b()
  var a;  // 当声明了a 预编译流程就好 找变量(形参和声明, 并设置成undefined)-> 实参 -> 函数提升 -> 赋值
  console.log('add内部', a)  //1
})()

8

(function add(a = 1, b = (function () {
  a = 2
  console.log('b内部', a)//2 函数b里面的a是整个形参作用域的
})()) {
  var a;  // 注意: 形参这里是立即执行函数 当声明了a 预编译流程就好 找变量(形参和声明, 并设置成undefined)-> 实参 -> 函数提升 -> 形参的默认值给到该变量
  console.log('add内部', a)  //2
})()

9

(function add(a = 1, b = function () {
  a = 2
  console.log('b内部', a)//2 函数b里面的a是整个形参作用域的
}) {
  b()
  console.log('add内部', a)  //2
})()