javascript中带有`this`绑定的括号的效果
我遇到了一个非常棘手的情况:javascript中带有`this`绑定的括号的效果,javascript,ecmascript-6,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 在上述情况下,为什么(0,C.method)会更改此的绑定?在JavaScript中使用时,会计算两个操作数,然
class C {
// class method are implicit in strict mode by default
static method() { return this === undefined; }
}
C.method(); // => false
(0,C.method)(); // => true
在上述情况下,为什么(0,C.method)
会更改此
的绑定?在JavaScript中使用时,会计算两个操作数,然后返回最右边的值。括号中的求值函数值没有其来源的上下文。这可以比作给变量赋值,赋值运算符=
的右侧在赋值之前进行求值:
(0, C.method)();
// ^^^^^^^^ evaluates here
var func = C.method;
// ^^^^^^^^ evaluates here
func();
一旦将函数放入变量中,它将丢失它来自的对象的所有上下文(除非使用了
bind
)。这一背景对我们来说很重要。调用函数时,如果函数不是对象的成员,则默认为全局对象;如果函数处于严格模式,则默认为未定义。()这是因为C.method
返回如下引用
{ base: C, referencedName: "method", strict: strictFlag }
当您使用该引用时,JS获取函数using,并提供引用的基础(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
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
上下文从类更改为全局,因此
此
未定义。您可能希望读取。@4castle如果通过var
声明并初始化内存,则有意义;但是表达式(0,C.method)
如何分配新的内存插槽呢?
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