Search code examples
javascriptarraysdictionaryconstructorprototype-programming

Passing a constructor to Array.map?


How can i do something like this:

var a = [1,2,3,4];
a.map(Date.constructor);

This code throws an Error on Google V8:

SyntaxError: Unexpected number

I'am also tried:

a.map(Date.constructor, Date.prototype)

with the same result.


Solution

  • The Date is a function, so the Date.constructor is a constructor of a function. Proper call of the Date object constructor looks like this:

    Date.prototype.constructor();
    

    Or just:

    Date();
    

    The problem here is to create an array of Date objects with time values from array a, but it is impossible to call the Date object constructor and pass an arguments to it without a new operator (ECMA-262 15.9.2).

    But it is possible for any object constructors that can be called as a functions with the same result as if i use the new operator (for instance the Error object constructor (ECMA-262 15.11.1)).

    $ var a = ['foo','bar','baz'];
    $ a.map(Error);
    > [ { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'foo' },
        { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'bar' },
        { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'baz' } ]