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

标签 javascript

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

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

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 运算符的情况下调用该函数,它将自动返回一个新实例。

例如,如果您没有这种保护措施,并且这样做...

var t = Terminal();

...然后 this 在执行 Terminal() 时会指向 window(或者你的全局对象,花哨的非浏览器家伙/gal),绝对不是您想要的。

通过确定 this 实际上是 Terminal 的实例,然后我们可以继续。否则,安全措施将返回一个新对象。

然后我们可以简单地使用这两种形式...

var t = Terminal(); // Will be same as `new Terminal()`

关于javascript - function F() { if (!(this instanceof F)) { return new F() }; ... },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211755/

相关文章:

javascript - 卡住了nodejs回调

javascript - 在javascript中连接分割字符串

javascript - 卸载外部JS文件的按钮

javascript - 如何使用枚举值作为数组的索引

javascript - 如何根据 JavaScript/jQuery 中查询字符串的值执行 if 条件?

javascript - 无法按模型选择元素

javascript - 在图 block 显示失败的地方显示替代图像/图 block (D3 Geo Tiles)

javascript - 通过传递参数设置超时

javascript - 将样式组件中的值与单位相乘

javascript - FabricJS HiDPI 获取图像数据