简体   繁体   中英

Create an array with or without `new`

There are two ways to create an array using the array constructor

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

I would say that the first (with the new keyword) is preferred or is it of no importance ?

UPDATE: In my case I use this type of array construction because I do:

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

If a function is meant to be used only as a constructor function, then one can use the common pattern,

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

Something similar to that would be done in the Array constructor as well.

Note: It is always better to use new , if you intend to use a function as a constructor function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM