Why do parentheses cause object to become unbound?

后端 未结 1 1651
清歌不尽
清歌不尽 2021-01-14 11:12

When I surround a new object invocation with parens and call a method on it immediately Node (or just v8 in general) will throw a \"TypeError: this.getName is not a function

相关标签:
1条回答
  • 2021-01-14 12:02

    You are depending on automatic semi-colon insertion and it isn't working the way you expect.

    This:

    Greeter.prototype.helloWorld = function() {
      console.log(`Hello ${this.getName()}`);
    }
    
    // Throws, this in any class methods are bound to the global
    (new Greeter('Olive')).helloWorld();
    

    is equivalent to:

    let mygreeter = new Greeter('Olive');
    
    let result_of_call = (function() {
      console.log(`Hello ${this.getName()}`);
    }(mygreeter));
    
    Greeter.prototype.helloWorld = result_of_call.helloWorld();
    

    You need to put a semi-colon after the previous expression to prevent the (...) being interpreted as "Call this function as an IIFE with arguments"

    Greeter.prototype.helloWorld = function() {
      console.log(`Hello ${this.getName()}`);
    };
    
    (new Greeter('Olive')).helloWorld();
    
    0 讨论(0)
提交回复
热议问题