Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

ecmascript 6 - The effect of parenthesis with `this` binding in javascript

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because C.method returns a reference like

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...