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; }
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()`
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With