6. this - cw84973570/Learning-notes GitHub Wiki
https://github.com/mqyqingfeng/Blog/issues/7
Reference是一个特殊类型,用于描述ECMAScript语言构造和类型。只存在于规范中的类型。
Reference是为了更好地描述语言的底层行为逻辑,解释诸如delete、typeof以及赋值等操作行为的。
Reference由三个部分组成: base Value referenced name strict reference
base value 就是属性所在的对象或者就是 EnvironmentRecord,它的值只可能是 undefined, an Object, a Boolean, a String, a Number, or an environment record 其中的一种。
问题:什么情况下是undefined?
GetBase: 返回reference的base Value.
GetBase(V). Returns the base value component of the reference V.
IsPropertyReference: 简单来说如果base value是一个对象,返回true
IsPropertyReference(V). Returns true if either the base value is an object or HasPrimitiveBase(V) is true; otherwise returns false.
GetValue: 返回具体的值。例如GetValue(Type(foo.bar)),即返回bar的值。
调用 GetValue,返回的将是具体的值,而不再是一个 Reference
如何确定this的值
看规范 11.2.3 Function Calls:
这里讲了当函数调用的时候,如何确定 this 的取值。
只看第一步、第六步、第七步:
1.Let ref be the result of evaluating MemberExpression. 简单来说就是()左边的部分
- If Type(ref) is Reference, then 如果Type左边的部分是Reference
a.If IsPropertyReference(ref) is true, then 如果左边的部分是对象
> i.Let thisValue be GetBase(ref). 让this的值为GetBase(ref),即base value的值
b.Else, the base of ref is an Environment Record 如果不是对象,则为Evironment Record
> i.Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref). 总是返回undefined
7.Else, Type(ref) is not Reference. Type(左边部分)不是reference,例如左边是算式的情况。
a. Let thisValue be undefined.
一句话总结:函数就是函数本身,它从来不属于任何对象,this的指向取决于调用形式。