本文介绍了function F(){if(!(this instanceof F)){return new F()}; ...}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造的用法是什么: function F(){if(!(this instanceof F)){return new F()}; ...}

我在Node的 pty.js 中找到了这个。这是原始代码:

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


推荐答案

这意味着如果功能在没有 new 运算符的情况下调用它,它将自动返回一个新实例。

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

...然后执行 终端()将指向窗口(或您的全局对象,花哨的非浏览器人/ gal),绝对 not 你想要什么。

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

这篇关于function F(){if(!(this instanceof F)){return new F()}; ...}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:43