12

I was looking for solutions for calling Javascript constructors with an arbitrary number of arguments, and found some good SO posts, which led me to believe that these three calls should work the same. However, at least in rhino and node.js, they do not:

1. f = Date.bind(Date, 2000,0,1)
2. g = Date.bind.call(Date, 2000, 0, 1)
3. h = Date.bind.apply(Date, [2000, 0, 1])

The first one has the desired result:

print(new f()) //=> Sat Jan 01 2000 00:00:00 GMT-0500 (EST)

But the other two don't:

print(new g()) //=> Thu Feb 01 1900 00:00:00 GMT-0500 (EST)
print(new h()) //=> Wed Jun 01 1904 00:00:00 GMT-0400 (EST)

So something's gone haywire somewhere. Thoughts on what? Is it just a bad idea to mix things like apply, bind, and/or call with new?

5
  • They all fail in IE 8 because there is no Date.bind. ;-)
    – RobG
    May 15, 2012 at 6:15
  • It seems to me that this is an inappropriate use of bind. It should be used to create funcion objects, but dates are Date objects, not functions, and can't be called. Also, without the use of bind or call or apply, the this value is Date anyway, so what's the point? Lastly, you aren't calling Date as a constructor but as a function.
    – RobG
    May 15, 2012 at 6:22
  • Sure, dates are Date objects, but Date itself is a function, and it's Date itself that I'm trying to bind to. Date is a function, so I bind it and get a new function, which I then use as a constructor by calling it with new. As I said at the top of the question, the actual point is to be able to call a constructor with a list of arguments determined at runtime.
    – Mark Reed
    May 15, 2012 at 11:57
  • 1
    Reading other comments, I think you've come to the realisation that javascript doesn't have classes. Takes a while, but eventually everyone gets there. :-) You can emulate lots of class based stuff, but Date (and probably Math) are exceptions or at least make it really difficult. That's why Date libraries use functions that call Date methods rather than attempt to "subclass" Date. Even Douglas Crockford gave up on complex "class" hierarchies, preferring simple objects.
    – RobG
    May 16, 2012 at 2:35
  • @RobG indeed. I was actually trying my hand at constructing a new method (like the one in Mr. Crockford's book, but without looking at his implementation) when I ran into this little conundrum.
    – Mark Reed
    May 16, 2012 at 4:12

2 Answers 2

34

The previously accepted answer was incorrect. You can use bind, call and apply with constructors to create new constructors just fine -- the only problem in your test is that you've forgotten that bind.apply and bind.call are applying and calling bind, not the constructor itself, so you gave the wrong arguments.

f = Date.bind(null, 2000,0,1)
g = Function.bind.call(Date, null, 2000, 0, 1)
h = Function.bind.apply(Date, [ null, 2000, 0, 1 ])

new f() //=> Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
new g() //=> Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
new h() //=> Sat Jan 01 2000 00:00:00 GMT-0500 (EST)

All three are instanceof Date.

Call's arguments are the execution context followed by the arguments to apply. Apply's arguments are the execution context and an array of arguments. Bind's arguments are the execution context followed by the arguments to bind.

So the arguments to apply, for example, are the context for which to apply bind (Date) followed by an array which is the arguments for bind (so the first array member is the bind's context argument). This is why it's confusing to call or apply bind; it feels strange to supply context arguments to both.

Note that, when using bind with constructors, the context argument is always ignored because 'new' explicitly creates a new context. I use null when the context argument is irrelevant to keep that clear, but it can be anything.

Meanwhile, apply and call in these examples do need to know that the context in which they are to apply/call bind is the Date function. I switched 'Date' to 'Function' where possible to help illuminate what is actually supplying context where. When we call apply or call on Date.bind, we are really calling apply or call on the bind method unattached to the Date object. The bind method in such a case could come from any function at all. It could be Number.bind.call(Date, null, 2000, 0, 1) and the result would be exactly the same.

If it's not obvious why, consider the difference between the following examples:

context.method();

and

var noLongerAMethod = context.method;
noLongerAMethod();

In the second case, the method has been divorced from its original context (...unless it was previously bound) and will behave differently if it was relying on 'this' internally. When we pull bind off any given function as a property, rather than executing it directly, it is simply another pointer to the generic bind method on Function.prototype.

Personally I don't think I've ever needed to call or apply bind, and it's hard to imagine a situation for which it would be a good solution, but binding constructors to create new constructors is something I've found very useful on occasion. In any case it's a fun puzzle.

1
  • 1
    This was a very helpful response. Thank you!
    – Mark Reed
    Sep 9, 2014 at 13:00
4

bind and apply / call only works work invocation to function but not constructor, so basically with native methods you cannot do this, one way is to write a bindConstruct method but it may involves extra complexity:

function bindConstruct(fn) {
    // since constructor always accepts a static this value
    // so bindConstruct cannot specify this
    var extraArgs = [].slice.call(arguments, 1);

    // create a 'subclass' of fn
    function sub() {
        var args = extraArgs.concat([].slice.call(arguments));
        fn.apply(this, args);
    }
    sub.prototype = fn.prototype;
    sub.prototype.constructor = sub;

    return sub;
}

This, actually, creates a subclass to your constructor.

Then your code:

var MyClass = function(x, y) {
    console.log(arguments);
    console.log(x + y);
}
var BindedMyClass = bindConstruct(MyClass, 1, 2, 3);
var c = new BindedMyClass(4, 5);
console.log(c instanceof MyClass);
console.log(c instanceof BindedMyClass);

You may also write this function to Function.prototype or as an extension to the native bind function.

3
  • 1
    Thanks, but sadly, this doesn't work properly, either. Date methods fail on any objects I create with my new "Date subclass" function with TypeError: Method called on incompatible object. Thus demonstrating once again that Javascript doesn't really have subclasses. Or classes at all, for that matter...
    – Mark Reed
    May 15, 2012 at 12:00
  • 1
    "bind and apply / call only works work invocation to function but not constructor" just isn't true; see below.
    – Semicolon
    Apr 21, 2014 at 4:25
  • A nice example of cargo cult. Constructors are nothing but ordinary functions, so you can use any of the Function.prototype methods on them. What makes a constructor special is the use of new to invoke it. Try calling a constructor directly and you'll get silly results, since this will have the wrong value and the code will set global variables instead of the attributes of a new object instance. The notion of class is mostly cosmetic, it's a nice wrapper around what you had to do by hand before ES6, namely create a "constructor" function and add methods in its prototype attribute.
    – kuroi neko
    Jul 26, 2021 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.