Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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. Here is the original code:

function Terminal(file, args, opt) {   if (!(this instanceof Terminal)) {      return new Terminal(file, args, opt);   }    var self = this      , env      , cwd      , name      , cols      , rows      , term; -------------------SKIP-----------------------------------   Terminal.total++;   this.socket.on('close', function() {      Terminal.total--;      self._close();      self.emit('exit', null);   });    env = null; } 
like image 216
exebook Avatar asked Mar 05 '14 23:03

exebook


2 Answers

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()` 
like image 152
alex Avatar answered Oct 05 '22 23:10

alex


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.

like image 35
Oriol Avatar answered Oct 05 '22 22:10

Oriol