Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

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

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;
}
question from:https://stackoverflow.com/questions/22211755/function-f-if-this-instanceof-f-return-new-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...