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

变量提升 #17

Open
YBFACC opened this issue Jun 13, 2020 · 0 comments
Open

变量提升 #17

YBFACC opened this issue Jun 13, 2020 · 0 comments

Comments

@YBFACC
Copy link
Owner

YBFACC commented Jun 13, 2020

变量提升

注意⚠️ 变量提升不适用于 let 、const。一般提及都是var、function。

提起 变量提升 就要提起 预编译。分为以下4步:

  1. 创建当前的活动对象。创建对应的执行上下文。
  2. 寻找函数形参,寻找var声明。设定为 undefined。
  3. 将实参与形参相互统一。
  4. 寻找函数声明挂载在当前活动对象上。函数名为 key,函数值为 value。

具体测试

变量提升忽略块级作用域

if (false) {
  var a = 'ybf'
}

console.log(a)//undefined

函数声明优先级会高于值声明

var a
function a() {}

console.log(a)//function...

参数与函数重名

function a(a1, b1) {
  
  function a1() {}
  console.log(a1)
}

a('a传参', 'b传参')//function a1() { … }

使用未声明的变量

function name() {
  var a = b = 'ybf'
}
name()
// console.log(a)//is not defined
console.log(b)//"ybf"

b 会直接挂载到全局变量上。

函数、形参、var声明重名

function a(a1, b1) {
  console.log(a1)//function

  var a1 = 'var'
  console.log(a1)//var

  function a1() {}
  console.log(a1)//var
}

a('a传参', 'b传参') 

可以看到形参直接没有出现,我们可以从预编译的过程中找到答案。

  1. 函数声明在最后声明,覆盖了形参。

  2. a1的赋值,覆盖了函数。

总结

函数声明优先级会高于值声明。

变量提升忽略 块级作用域

如果一个值没有声明就使用,不会变量提升。但是当执行时,会直接挂载到全局环境上。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant