Thanks to Function.prototype.bind
there's a nice way to create objects with parametric arguments:
var d = new (Function.prototype.bind.apply(Date, [null, 2012, 8, 3]));
console.log(d); // => Mon Sep 03 2012 00:00:00 + timezone
Unfortunately, bind isnt supported by IE8 and older, but that's covered by many common polyfills. The one on MDN is perhaps the most common:
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
But this causes odd results on IE:
console.log(d); // throws "Date.prototype.toString: 'this' is not a Date object"
Something similar also for custom classes, not just native objects.
I'm a bit lost in this. Is it possible to solve this just changing the definition of Function.prototype.bind
? I fear it's not.