ste*_*ang 2 javascript ecmascript-6
我遇到了一个非常棘手的案例:
class C {
// class method are implicit in strict mode by default
static method() { return this === undefined; }
}
C.method(); // => false
(0,C.method)(); // => true
Run Code Online (Sandbox Code Playgroud)
为什么要(0, C.method)改变this上述情况下的绑定?
那是因为C.method返回像这样的引用
{ base: C, referencedName: "method", strict: strictFlag }
Run Code Online (Sandbox Code Playgroud)
当你调用它时,JS使用带有该引用的GetValue获取函数,并提供reference(C)的基础作为this值.
CallExpression : MemberExpression Arguments
1. Let ref be the result of evaluating MemberExpression. // <-- The reference
2. Let func be ? GetValue(ref). // <-- The function
4. If Type(ref) is Reference, then
a. If IsPropertyReference(ref) is true, then
i. Let thisValue be GetThisValue(ref). // <-- C
Run Code Online (Sandbox Code Playgroud)
但是,当您使用逗号运算符时,您直接获取函数,而不是引用.
Expression : Expression , AssignmentExpression
1. Let lref be the result of evaluating Expression.
2. Perform ? GetValue(lref). // <-- 0
3. Let rref be the result of evaluating AssignmentExpression.
4. Return ? GetValue(rref). // <-- The function
Run Code Online (Sandbox Code Playgroud)
由于没有引用,JS无法知道基础对象,因此当您调用它时提供undefined的this值为.
CallExpression : MemberExpression Arguments
1. Let ref be the result of evaluating MemberExpression. // <-- The function
2. Let func be ? GetValue(ref). // <-- The function
5. Else Type(ref) is not Reference,
1. Let thisValue be undefined. // <-- undefined
Run Code Online (Sandbox Code Playgroud)