Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  108] [ 5]  / answers: 1 / hits: 5863  / 10 Years ago, wed, march 5, 2014, 12:00:00

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;
}

More From » javascript

 Answers
6

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()`

[#47139] Wednesday, March 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donovanjasek

Total Points: 465
Total Questions: 103
Total Answers: 113

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
;