结构的用法是什么: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/