2017-01-08 23 views
1

我遇到一個非常棘手的情況下,括號的作用:用`this`結合在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)改變的this在上述情況下的結合?

+0

上下文從類更改爲全局,所以'this'未定義。 – Li357

+0

您可能想要閱讀[this'如何使用對象方法的MDN描述](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Thisis_As_an_object_method)。 – 4castle

+0

@ 4castle如果一個內存是通過'var'聲明和初始化的,這是有道理的;但是'(0,C.method)'表達式如何分配新的內存插槽? – steveyang

回答

3

這是因爲C.method返回類似

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

基準時call it,JS獲得使用GetValue與參考值的功能,並提供參考(C)作爲this值的基礎。

CallExpression : MemberExpressionArguments 

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 

然而,當你使用comma operator,你直接獲得的功能,而不是參考。

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作爲this值。

CallExpression : MemberExpressionArguments 

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 
3

當您在JavaScript中使用comma operator時,將對兩個操作數進行評估,然後返回最右邊的值。來自括號的評估函數值沒有來自哪裏的背景。這可以比喻爲一個變量,在賦值運算符=的右側被評爲值分配之前分配一個值:

(0, C.method)(); 
// ^^^^^^^^ evaluates here 

var func = C.method; 
//   ^^^^^^^^ evaluates here 
func(); 

一旦一個功能被放入一個變量,它失去了一切它來自哪個對象的上下文(除非使用bind)。此背景對determining the value of this很重要。當函數被調用而不是對象的成員時,它將默認爲全局對象,如果函數處於嚴格模式,則缺省爲undefined。 (MDN