3

Most libraries with enumerator methods (even native JavaScript, I think) allow the passing of a context for the iterator.

function reduce(iterator, memo, context){
    this.each(function(item, idx, list){
        memo = iterator.call(context, memo, item, idx, list)
    });
    return memo;
}

The question is why when bind can easily offer the same feature?

stooges.reduce(function(memo, stooge){
  ...
}, context) // as argument vs...

stooges.reduce(function(memo, stooge){
  ...
}.bind(context))

Is this something that exists for the time being since bind is not readily available on all platforms? Or is it simply because there is less overhead to calling than binding? I always read that the fewer arguments a function takes the better. That is a function taking 0 args is better than one taking 1 is better than one taking 2, etc.

Mario
  • 6,572
  • 3
  • 42
  • 74
  • 1
    Almost certainly because `Function.bind` is not (yet) supported by all browsers, but this is kind of a subjective question. You might be better off asking some library authors. – Matt Ball Jun 28 '13 at 02:28
  • Does that stand to reason that when it is, this context passing will change? – Mario Jun 28 '13 at 02:30
  • It'll change when the authors change it, and no sooner. – Matt Ball Jun 28 '13 at 02:34
  • 2
    It should be preferred over `.bind()` as it's a much lighter weight solution. –  Jun 28 '13 at 02:34
  • @CrazyTrain "lighter weight" in what way? – Matt Ball Jun 28 '13 at 02:35
  • 2
    @MattBall: You're not creating a new function object with the context argument. –  Jun 28 '13 at 02:35
  • New function syntax in ES6 with lexically defined `this` will render them both obsolete. –  Jun 28 '13 at 02:38
  • Calling the *this* keyword "context" doesn't seem appropriate. The term context is used in EMCA-262 to reference [execution context](http://www.ecma-international.org/ecma-262/5.1/#sec-10), which is a lot more than simply whatever *this* references. Given that in ES5 *this* may be undefined or null, it seems even more inappropriate there. I think *this* should simply be called *thisObj* or *thisRef*, which is the same number of characters as *context* and much more explicit. – RobG Jun 28 '13 at 03:36

1 Answers1

2

Using .bind create and return a new function. In some case, you prefer to limit the number of objects/variables created by the javascript VM so you leverage the garbage collector cleaning cycles.

Also, bind is known to be quite slower than "emulated" binding solutions (using call and apply): Why is Function.prototype.bind slow?

Otherwise, it's often nicer and more readable to pass a context as a parameter.

ES6 arrow functions will allow to keep lexical this, so it'll be even easier:

// considering object context
var self = this;
stooges.reduce((memo, stooge) => (this === self));
Community
  • 1
  • 1
Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134