Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IIFE 作用域问题 01 #8

Open
iotale opened this issue Aug 9, 2020 · 0 comments
Open

IIFE 作用域问题 01 #8

iotale opened this issue Aug 9, 2020 · 0 comments
Labels

Comments

@iotale
Copy link
Owner

iotale commented Aug 9, 2020

在ES5中主要使用匿名函数【IIFE】的方式来达到块级作用域的效果

var name = 'Tom';
(() => {
  if (typeof name === 'undefined') {
    var name = 'jeck';
    console.log('1:', name);
  } else {
    console.log('2:', name);
  }
})()

// 结果输出 “1: jeck”
  • 从外部看,iife形成块级作用域,将函数内部与全局的环境隔离开(所以立即执行函数在查看内部有没有name变量的时候不会受到全局变量的影响)
  • 在iife形成的块级作用域内
    • ES5不存在块级作用域,也就是if语句后面的{}并没有形成块级作用域
    • var声明的变量存在变量提升,虽然 var name 在if条件语句内,但是也会发生变量提升
    • 由于iife形成了块级作用域,所以var name只会提升到这个作用域的最上面
      所以,上面代码实际执行顺序如下:
var name = 'Tom';
(() => {
  var name;
  if (typeof name === 'undefined') {
    name = 'jeck';
    console.log('1:', name);
  } else {
    console.log('2:', name);
  }
})()

变换

var name = 'Tom';
(() => {
  if (typeof name === 'undefined') {
    name = 'jeck';
    console.log(name);
  } else {
    console.log(name);
  }
})()

// 结果是 Tom
  • 首先在进入函数作用域当中,获取name属性
  • 在当前作用域没有找到name(因为没有使用var声明name,也就不存在变量提升,所以执行 typeof name 时在当前作用域内找不到name)
  • 通过作用域链找到最外层,得到name属性
  • 由于在外层作用域name已经赋值 name = 'Tom',所以条件语句执行else的内容,得到Tom
@iotale iotale added the JS label Aug 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant