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

后端 未结 3 1498
梦谈多话
梦谈多话 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:51

    It's just to make sure it will work even if F is called without new.

    When you call F with new, in that function this is the new instance.

    Then, if this is not an instance of F (!(this instanceof F)), then that means that F was not called using new. In this case, F calls itself, now with new.

提交回复
热议问题