2

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.

Barett
  • 5,826
  • 6
  • 51
  • 55
MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • Why do you even need to reference `Function.prototype.bind`? Isn't it sufficient to just use `Date.apply(Date, [2012, 8, 3]);`? – Peter Olson Sep 03 '12 at 01:43
  • @PeterOlson You get a string using that, not a `Date` object. Moreover, a string of the current time. It's like calling `Date()`. – MaxArt Sep 03 '12 at 01:54
  • 1
    Calling a the function returned by `Function.prototype.bind.apply(Date, [null, 2012, 8, 3]);` returns a string too. It does *not* create a Date object. `new d()` seems to work though, if this is what you mean. (`console.log(d);` gives me `function () { [native code] }` only). If all what you want is use `.apply` with `new`, have a look at http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible. – Felix Kling Sep 03 '12 at 01:58
  • @FelixKling Sorry, there was a little mistake in the code: the `new` keyword was missing. Man, I'm too sleepy now... – MaxArt Sep 03 '12 at 02:30
  • JS provides SO MANY ways for shooting your feets – zerkms Sep 03 '12 at 02:32

0 Answers0