Skip to content

数据类型 2.6函数 1.5函数声明的提升可修改 #251

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

Closed
fhzm opened this issue Aug 27, 2022 · 3 comments
Closed

数据类型 2.6函数 1.5函数声明的提升可修改 #251

fhzm opened this issue Aug 27, 2022 · 3 comments

Comments

@fhzm
Copy link

fhzm commented Aug 27, 2022

注意,如果像下面例子那样,采用function命令和var赋值语句声明同一个函数,由于存在函数提升,最后会采用var赋值语句的定义。

var f = function () {
  console.log('1');
}

function f() {
  console.log('2');
}

f() // 1

上面例子中,表面上后面声明的函数f,应该覆盖前面的var赋值语句,但是由于存在函数提升,实际上正好反过来。
以上是原文
修改建议
变量提升发生在预编译的时候,而预编译又发生在代码执行之前, 如果是在全局作用域下 会先找var 定义的变量名作为作用域下是属性名,值为undefined 然后找函数声明的函数名作为作用域下的属性名,它的值就是函数体,如果已经有相同的属性名就直接将函数体赋值给它,所以上面的代码如果把f()放在var f 之前执行它执行的结果是2,

f() // 2
var f = function () {
  console.log('1');
}

function f() {
  console.log('2');
}

放到最后执行结果为1的原因是代码一行一行往下走,var f 与function f都提升上去 了 下面只剩下 f=function(){console.log(2)} f()
而在函数作用域里面,过程与全局作用域大致相同,只是会先找var定义的变量名以及形参名,然后将实参的值赋值给形参,接着再找函数声明,并赋值函数体,
简单理解就是不管是全局作用域还是函数作用域,变量 提升的变量名与变量值优先使用的是函数声明的函数名以及函数体,其次才是形参名,形参值,最后才是声明命令声明的变量名以及所赋给的值
如果采纳修改建议还望阮老师能够自己组织一下语言

@shibor
Copy link

shibor commented Aug 27, 2022 via email

@ruanyf
Copy link
Contributor

ruanyf commented Aug 27, 2022

原文比较简单。

@ruanyf ruanyf closed this as completed Aug 27, 2022
@fhzm
Copy link
Author

fhzm commented Aug 27, 2022 via email

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

No branches or pull requests

3 participants