gpt4 book ai didi

javascript - 创建一个包含或不包含 `new` 的数组

转载 作者:行者123 更新时间:2023-11-29 18:04:54 24 4
gpt4 key购买 nike

有两种方法可以使用数组构造函数创建数组

new Array(1,2,3)
Array(1,2,3)

我会说第一个(使用 new 关键字)是首选还是不重要?

更新:在我的例子中,我使用这种类型的数组构造,因为我这样做:

new Array(someNum).join('x');

最佳答案

如果一个函数只用作构造函数,那么可以使用通用模式,

function ConstructorFunction() {
// If the current object is not an instance of `ConstructorFunction`
if (!(this instanceof ConstructorFunction)) {
return new ConstructorFunction();
}
...
}

Array 构造函数中也会做类似的事情。

注意:如果您打算将函数用作构造函数,最好使用new

关于javascript - 创建一个包含或不包含 `new` 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com