Geo*_*pty 2 javascript prototype apply
作为日期/温度散点图的数据,我希望能够使用类似日期的字符串来键入数据,以下是我设计的结构:
var dateTemperatures = {
'[2016,8,29]': {low: 63, high: 94},
'[2016,9,2]': {low: 59, high: 81},
'[2016,9,1]': {low: 58, high: 85}
}
Run Code Online (Sandbox Code Playgroud)
我的想法是,我可以在键上调用JSON.parse,并具有创建日期所需的参数.然后我发现这个答案#1对如何创建一个对象,利用两者的结合apply,并new .... ()使用了以下取代,特别是Something具有Date:
var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));
Run Code Online (Sandbox Code Playgroud)
它就像一个魅力,例如在我为订购"日期"键而设计的以下功能中:
function orderTemperatureDates(dateTemperatures) {
var orderedDates = [];
for (var temperatureDate in dateTemperatures) {
var YMD = JSON.parse(temperatureDate);
YMD.unshift(null); //standard first argument to .apply()
orderedDates.push(new (Function.prototype.bind.apply(Date, YMD)));
}
return orderedDates.sort(function(a,b){return a.getTime() - b.getTime()});
}
Run Code Online (Sandbox Code Playgroud)
CONSOLE /日志/输出:
[Thu Sep 29 2016 00:00:00 GMT-0500 (Central Daylight Time), Sat Oct 01 2016 00:00:00 GMT-0500 (Central Daylight Time), Sun Oct 02 2016 00:00:00 GMT-0500 (Central Daylight Time)]
Run Code Online (Sandbox Code Playgroud)
回到引用的Stackoverflow答案中的示例行,这是如何工作的?因为我的理解,根据这里的文档,null可以是apply其余参数后面的第一个参数,但在示例和我的代码中,null和所有剩余的参数是同一个数组的一部分.
我的理解是,这
null可能是apply其余论点所遵循的第一个论点
是的,你可以传递null作为第一个参数,apply 当你想要this方法中的值时null(或通常不关心它).但这不是这种情况.
在new (Function.prototype.bind.apply(Date, [null, 2016, 8, 29]))我们不null作为第一个参数传递apply,因为我们不希望这样.我们正在应用该bind方法,我们需要将其应用于Date其余参数.这个电话相当于
new (Date.bind(null, 2016, 8, 29))
Run Code Online (Sandbox Code Playgroud)
我们null作为第一个参数传递的位置bind,因为我们不关心在使用new关键字调用绑定函数时将被忽略的值.
看看这个例子:
function constructor(a, b, c) {
"use strict";
console.log(this, a, b, c);
}
var bound = constructor.bind(null, 1, 2, 3);
bound();
new bound();Run Code Online (Sandbox Code Playgroud)
如果您知道YMD总是有三个元素,那么写起来会更容易new Date(YMD[0], YMD[1], YMD[2]).如果您使用的是ES6,则还可以使用扩展语法new Date(...YMD)进行调用.