There certainly is a reason, it makes for (arguably) cleaner code in some cases (quite arguably not so in this example =), and can be used to have one *less* function on the stack than if you made a closure (e.g. fs.unlink(fn2, fs.rename.bind(fs, fn1, fn2, cb)); ) - at least it appears that a callable made with .bind() doesn't actually add a function to the stack in V8 when called.
I don't think bind()'s "primary" purpose is "passing scopes", that's just one of its uses. It's equally valid (and useful) to use it to bind parameters to a function as it is to bind a "this" value. Though, with the performance of it seemingly getting worse with each new V8 version compared to closures (or, rather, closures getting faster, perhaps ;), it might not be a good idea to use it. In fact, from the performance and memory results so far, it seems like making a closure that uses .call() may be more efficient than .bind anyway in the case where you want to bind a new "this" value... On Jun 8, 9:45 pm, Rick Waldron <[email protected]> wrote: > On Saturday, June 9, 2012 at 12:21 AM, Jimb Esser wrote: > > By "binding more than once", I mean binding the same original function > > multiple times (with different parameters), not binding the result of > > a previously bound function. > > > An example of using bind instead of a closure: > > original: > > function backupFile(filename, cb) { > > fs.unlink(filename + '.bak', function(err) { > > fs.rename(filename, filename + '.bak', cb); > > }); > > } > > Using bind and no run-time function creation: > > function backupFile(filename, cb) { > > fs.unlink(filename + '.bak', step2.bind(undefined, filename, cb)); > > } > > function step2(filename, cb, err) { > > fs.rename(filename, filename + '.bak', cb); > > } > > I would agree that a function expression makes more sense in this case -- > there is actually no reason to use bind() here at all. In fact, the > comparison still doesn't balance because you're forcing bind() into a role > that doesn't make sense. Additionally, this example is wantonly adding a > function to the stack. > > bind()'s primary use case is passing one function's scope to another or > "sharing" a "scope" (represented by an object) between with an unrelated > functions. > > Rick > -- Job Board: http://jobs.nodejs.org/ Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines You received this message because you are subscribed to the Google Groups "nodejs" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nodejs?hl=en?hl=en
