这是一个新手查询.我经历了几个类似的帖子,但他们没有给我足够的帮助.这篇文章有两个查询,但由于它们的根似乎是相同的,因此我将它放在一起.
我遇到了以下代码段:
var Server = module.exports.Server = function Server(listener) {
if (!(this instanceof Server)) return new Server(listener);
//other code
}
module.exports.createServer = function(listener) {
return new Server(listener);
};
Run Code Online (Sandbox Code Playgroud)
我无法理解使用 if (!(this instanceof Server)) ;
何时可以在此处指向服务器?
我尝试对此进行快速测试:
var createTest = function(){
console.log(this.toString());
return new Test();
};
var Test = function Test(){
console.log(this instanceof Test);
console.log(this.toString());
if (!(this instanceof Test))
{
return new Test();
}
}
var tester = createTest();
Run Code Online (Sandbox Code Playgroud)
哪个输出:
[object global]
true
[object Object]
Run Code Online (Sandbox Code Playgroud)
这进一步困扰了我为什么this.toString打印[object Object] - 不应该是[object Test]?
谢谢 !
这是一个用来制作new
可选项的习语.例如:
function TraditionalTest() {
}
function IdiomaticTest() {
if(!(this instanceof IdiomaticTest)) return new IdiomaticTest();
}
console.log(new TraditionalTest()); // [object Object]
console.log(TraditionalTest()); // undefined
console.log(new IdiomaticTest()); // [object Object]
console.log(IdiomaticTest()); // [object Object]
Run Code Online (Sandbox Code Playgroud)
至于为什么它[object Object]
不是[object Test]
,我不知道它为什么这样定义,但这是它的定义方式:
toString
调用该方法时,将执行以下步骤:
- 如果
this
值为undefined
,则返回"[object Undefined]
".- 如果
this
值为null
,则返回"[object Null]
".- 设O是调用ToObject传递
this
值作为参数的结果.- 设class为O的[[Class]]内部属性的值.
- 返回String值,该值是连接三个字符串"
[object
",类和"]
"的结果.
[[Class]]在规范中被多次引用,但它只代表内置类型:
Arguments
Array
Boolean
Date
Error
Function
JSON
Math
Number
Object
RegExp
String