Hacker News new | past | comments | ask | show | jobs | submit login

Bind creates a function, which you can pass around as a value, and does not execute the function you give it immediately.

Both call and apply call the function it's given immediately.

That's why bind is useful in the context of event handlers--you want code to run at some later time. If you do this with 'apply', you still need a wrapper function.

Moreover, there is some manual manipulation of the `arguments` special object you need to do in order to get this to work with apply. Without bind you'd have to do something like

    function tweetWithType(tweetType) {
        return function() {
            var newArgs = Array.prototype.slice.call(arguments);
            newArgs.unshift(tweetType);
            this.handleStreamEvent.apply(this, newArgs);
        };
    }
to be able to call it like

    this.on('tweet', tweetWithType('tweet'));
and you STILL wouldn't be right, because `this` within tweetWithType is not the `this` you expect. You'd have to do the whole

    var self = this;
thing.



Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: