# 执行上下文

执行上下文 {
变量对象
作用域链 -> 函数的作用域在函数定义的时候就决定了
this
}

# this

调用场景
var obj = {a: 1, b: function(){console.log(this);}}

  1. 作为对象调用时,指向该对象 obj.b(); // 指向obj
  2. 作为函数调用, var b = obj.b; b(); // 指向全局window
  3. 为构造函数调用 var b = new Fun(); // this指向当前实例对象
  4. 作为call与apply调用 obj.b.apply(object, []); // this指向当前的object

规范解读

var value = 1;

var foo = {
  value: 2,
  bar: function () {
    return this.value;
  }
}

//示例1
console.log(foo.bar()); // 2
//示例2
console.log((foo.bar)()); // 2
//示例3
console.log((foo.bar = foo.bar)()); // 1
//示例4
console.log((false || foo.bar)()); // 1
//示例5
console.log((foo.bar, foo.bar)()); // 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

var Reference = { base: foo, name: 'bar', strict: false };

  1. 计算 MemberExpression 计算结果 foo.bar(就是()前面的)

  2. foo 是 reference 类型 IsPropertyReference(ref) 是 true (base value 是个对象,IsPropertyReference true)

  3. this = GetBase(ref)

  4. 运算符导致 getValue(ref), 一旦getValue, ref就不是 reference, this undefined, 隐私转换全局对象

# 其他

this 实际上是在函数被调用时建立的一个绑定,它指向 什么 是完全由函数被调用的调用点来决定的。

最后更新时间: 8/12/2021, 4:22:34 PM