function F() { if (!(this instanceof F)) { return new F() }; … }

后端 未结 3 1465
梦谈多话
梦谈多话 2020-12-01 01:59

What is the usage of the construct: function F() { if (!(this instanceof F)) { return new F() }; ... }?

I found this in a pty.js for Node.

3条回答
  •  攒了一身酷
    2020-12-01 02:26

    It means that if the function was called without the new operator, it will automagically return a new instance.

    For example, if you didn't have this safeguard, and did this...

    var t = Terminal();
    

    ...then the this while executing Terminal() would point to window (or your global object, fancy non-browser guy/gal), definitely not what you want.

    By determining that this is in fact an instance of Terminal, then we can proceed. Otherwise, the safeguard returns a new object.

    Then we can simply use both forms...

    var t = Terminal(); // Will be same as `new Terminal()`
    

提交回复
热议问题