前端的坑【02】 关于我对js函数内变量取值的误解


测试

今天突然发现了这个问题,有点颠覆三观(我太菜了

直接看一段代码

var count = 10;
 
function a() {
   return count + 10;
}
 
function b() {
   var count = 20;
   return a();
}
 
console.log(b());   // 20

初次看到十分迷惑,这不应该返回30吗?

写了一段代码测试一下

function test(){
    console.log(a)
}

let a = 10

{
    let a = 20
    test()  // 10
}

test()  // 10

我对js的误解是:我以为函数内变量是在运行时对外层变量进行 动态 引用。但事实显然不是那样,应该是: 函数在定义时内部变量静态应用了外部变量的地址

验证一下猜想

function test(){
    console.log(a)
}

let a = 10
test()

a = 20
test()

最后一个疑问 静态绑定和this有关吗?

function test(){
    console.log(a)
}
let a = 10
let obj = {
    a: 20
}

test()          // 10
test.call(obj)  // 10

验证一下,绑定的过程并不受this的影响,应该是直接引用了上层变量a的地址

summary

js函数内变量对外层的引用并不是运行时的动态绑定,而是函数定义时对地址的静态引用


Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC