请考虑以下代码片段:-
function Custom(){}
// prints {}
console.log(Object());
// prints []
console.log(Array());
// prints undefined
console.log(Custom())
// prints {}
console.log(new Custom());
我知道自定义函数构造函数需要一个前缀为new
关键字来绑定this
。为什么这对Array
和Object
构造函数不是必需的?
数组构造函数说:
当作为函数而不是构造函数调用时,还会创建和初始化新的 Array 对象。因此,函数调用 Array(...) 等效于具有相同参数的对象创建表达式 new Array(...)。
对象构造函数说:
- 如果 NewTarget 既不是未定义的也不是活动函数,则 a. 退货 ?OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
- 如果值未定义或为空,则返回 !OrdinaryObjectCreate(%Object.prototype%).
- 返回!ToObject(value)。
因此,明确指出,其中任何一个都不需要new
。
(不过,您可能永远不应该使用Object
或Array
作为构造函数,无论是否带有new
- 最好使用对象和数组文字)
如果需要,在 Custom 中自己实现这种事情是微不足道的 - 检查该函数是否使用new
调用,如果没有,则显式返回一些内容:
function Custom(){
if (!new.target) {
return new Custom();
}
}
console.log(Custom())
console.log(new Custom());
Custom, Object, and Array
都是函数。当您调用它们时,即Object()
,打印的值是函数的返回值。Object
和Array
分别返回一个新的空对象和数组。而Custom
函数不返回任何内容,因此打印undefined
。
当您使用new
调用函数时,将通过调用函数作为构造函数来创建一个对象。正如其中一条评论提到的,这提供了有关new
关键字的更多详细信息。