The effect of parenthesis with `this` binding in javascript

后端 未结 2 428
庸人自扰
庸人自扰 2020-12-20 00:59

I encounter a very tricky case:

class C {
  // class method are implicit in strict mode by default
  static method() { return this === undefined; }  
}

C.me         


        
2条回答
  •  旧时难觅i
    2020-12-20 01:42

    When you use the comma operator in JavaScript, both operands are evaluated, and then the right-most value is returned. The evaluated function value that comes out of the parentheses has no context of where it came from. This can be likened to assigning a value to a variable, where the right-hand side of the assignment operator = is evaluated before the value is assigned:

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

    Once a function is put into a variable, it loses all context of what object it came from (unless bind is used). This context is important to determining the value of this. When a function is called without being the member of an object, it defaults to the global object, or undefined if the function is in strict mode. (MDN)

提交回复
热议问题