Skip to content

This & Context

版本

不同版本的 nodejs 和 浏览器在处理不同的脚本上下文会有不同的策略

var length = 10;
function print(){
    console.log(this.length)
}
print()
以上代码在Node v10 和 Node v19(可能更早) 上的表现不同

自动上下文绑定

当函数 被添加到一个对象(数组,object,不包括Map)中,直接索引并调用会自动为其设置调用上下文为这个对象,但是如果将函数提取到变量中, 在调用则调用上下文为脚本上下文,

var length = 10;
function print() {
  console.log(this,this.length);
}
const a = [print];
a[0]() // 1
const b = {p:print,length:2};
b['p']() // 2
let foo = b['p']
foo() // 10

references: (JavaScript Execution Context – How JS Works Behind the Scenes)[https://www.freecodecamp.org/news/how-javascript-works-behind-the-scene-javascript-execution-context/]