4 ms·
It's not entirely clear to me how bind is different than apply.
by geuis 13y ago
It's not entirely clear to me how bind is different than apply.
- shadowfiend 13y agoThe key difference is that bind returns a function with the updated this/argument bindings, while apply actually runs the function.
- deleted 13y ago[deleted]
- Touche 13y agoBind creates a function, apply calls a function.
- timothya 13y agoThe big difference is that unlike `apply` (and `call`), `bind` does not call the function, it just gives you a new function that you have to call later (or use as an event handler). `bind` returns a new function, which has it's context `this` set to whatever you pass in, along with arguments partially applied. `apply` calls the function, using the context object you provide and the arguments provided in an array. (`apply` also has a sister function `call`, which also calls the function with the context object you provide and the arguments you provide individually).
- wging 13y agoBind 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.
- deleted 13y ago[deleted]