在javascript中使用“this”绑定的括号的效果 [英] The effect of parenthesis with `this` binding in javascript

查看:159
本文介绍了在javascript中使用“this”绑定的括号的效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个非常棘手的情况:

I encounter a very tricky case:

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)在上述情况下更改的绑定

Why (0, C.method) changes the binding of this in the above case?

推荐答案

因为 C.method 返回像

{ base: C, referencedName: "method", strict: strictFlag }

当您调用它,JS使用 GetValue ,并提供引用的基础( C )作为这个值。

When you call it, JS obtains the function using GetValue with that reference, and provides the base of the reference (C) as the this value.

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

但是,当您使用逗号运算符,你直接得到函数,而不是

However, when you use the comma operator, you directly get the function, not the reference.

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

由于没有参考,JS无法知道基数对象,所以当你调用它提供 undefined 作为这个值。

Since there is no reference, JS can't know the base object, so when you call it provides undefined as the this value.

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

这篇关于在javascript中使用“this”绑定的括号的效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆