将构造函数传递给Array.map?
我该怎么做:
var a = [1,2,3,4];
a.map(Date.constructor);
此代码在Google V8上引发错误:
This code throws an Error on Google V8:
SyntaxError: Unexpected number
我也尝试过:
a.map(Date.constructor, Date.prototype)
具有相同的结果。
Date是一个函数,因此Date.constructor是函数的构造函数。
正确调用Date对象构造函数如下所示:
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();
或者只是:
Date();
这里的问题是创建一个Date对象数组,其时间值来自数组 a
,
但无法调用Date对象构造函数并在没有 new
运算符的情况下向其传递参数(ECMA-262 15.9.2)。
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).
但任何可以作为函数调用的对象构造函数都可能具有与i相同的结果使用 new
运算符(例如Error对象构造函数(ECMA-262 15.11.1))。
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' } ]