执行上下文与执行上下文栈

变量提升与函数提升

变量声明提升
通过var定义的变量 在定义之前就可以访问到
值 undefined
函数声明提升
通过function声明的函数 在之前就可直接调用
值: 函数定义(对象)

    var a = 3
    function fn(){
        console.log(a);  // a  变量提升 undefined
        var a =4 // 
    }
    fn()

    console.log(b);
    var b =3
    fn2()
    fn3
    function fn2() {
        console.log("2");
    }

    var fn3 = function () {
        console.log('3');
    }

执行上下文

  1. 代码分类
    全局代码
    函数(局部)代码
    2. 全局执行上下文
    • 在执行全局代码前将window确定为全局执行上下文
    • 对全局数据进行预处理
      var定义的全局变量 undefined 添加为 windows属性
      function声明的全局函数 赋值(fn) 添加为window的方法
      this === window
    1. 函数执行上下文
      • 在调用函数,准备执行函数体之前,创建对应的函数执行上下文对象
      • 对局部数据进行预处理
        形参变量----赋值(实参)—添加为执行上下文对象
        arguments—赋值(实参列表),添加为执行上下文的属性
        var定义的局部变量 undefined 添加为执行上下文的属性
        function声明的函数----赋值(fn) 添加为执行上下文的方法
        this – 调用函数的对象
console.log(a1,window.a1);
   a2()
   var a1 =3
   function a2() {
       console.log('22');
   }
   function fn () {
       console.log(this); // window
       console.log(arguments) // 维数组 2,3
       var a = 3
       function fun() {
           console.log(this);
           console.log('fun');
       }
       fun()
   }
   fn() 

执行上下文栈

1.在全局代码执行前 JS引擎就会创建一个栈来存储管理所有的执行上下文对象
2.在全局执行上下文(window)确定后 将其添加在栈中(压栈)
3.在函数执行上下文创建后,将其添加到栈中(压栈)
4.在当前函数执行完成后,将栈顶的对象移除(出栈)
5.当所有的代码执行完毕之后,栈中只剩下window

console.log('gb: '+ i) // undefined
  var i = 1
  foo(1)
  function foo(i) {
    if (i == 4) {
      return
    }
    console.log('fb:' + i)  // 1
    foo(i + 1) //递归调用: 在函数内部调用自己
    console.log('fe:' + i)
  }
  console.log('ge: ' + i) // 1
  /*\
  foo(){
      log 1
      foo(){
          log2
          foo(){
              log 3
              log 3
          }
          log 2
      }
      log 1
  }
  */
 /*
   测试题1:  先执行变量提升, 再执行函数提升
   */
  function a() {}
  var a
  console.log(typeof a) // 'function'


  /*
   测试题2:
   */
  if (!(b in window)) {
    var b = 1
  }
  console.log(b) // undefined

  /*
   测试题3:
   */
  var c = 1
  function c(c) {
    console.log(c)
    var c = 3
  }
  c(2) // 报错
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值