0

I am reading some node code written by my ex-colleague. i am not a proficient javascript programmer, but i see lot of code that looks to me like syntactic sugar. for eg:

_.bind(this._work, this),

is not this exactly same as calling

this._work
konquestor
  • 1,308
  • 3
  • 15
  • 29
  • `bind` and `extend` are popular underscore methods (underscore being a js library). See [_.bind](http://underscorejs.org/#bind) and [_.extend](http://underscorejs.org/#extend) for details – csum Mar 22 '16 at 22:33
  • i know that. i am asking does above lines of code need them? – konquestor Mar 22 '16 at 22:33
  • Whether .bind() is needed depends on the context, and you haven't shown the context. Calling .bind without using its return value doesn't call your .work() function. If the return value is passed to some other function as a callback then you most likely *do* need .bind(). – nnnnnn Mar 22 '16 at 22:43
  • Agreed that context is important for `bind`. Also, in terms of `_.extend`, I don't think you need the assignment part. `extend` modifies the existing object, so you just need `_.extend(WorkerQueue.prototype, { ... })`. And yes you do want to use `extend` so that you can extend the object rather than wiping it out with a new assignment. – csum Mar 22 '16 at 22:54
  • Please ask one question per post only. Your second is a duplicate of https://stackoverflow.com/questions/17474390/defining-a-javascript-prototype, btw. – Bergi Mar 22 '16 at 23:43
  • `this._work` is not *calling* anything. Most likely it's getting passed around, which is the reason [why it needs to be bound](http://stackoverflow.com/q/20279484/1048572). – Bergi Mar 22 '16 at 23:44

1 Answers1

2

This creates a copy of the function with this bound to the correct object. This can be useful when you're passing functions around.

function log(msg) {
  document.querySelector('pre').innerText += msg + '\n';
}

var _ = {
  bind: function(f, self) {
    // Simplified bind implementation
    return f.bind(self);
  }
};

function runFunc(f) {
  f();
}

var obj = {
  myName: 'Mike',
  printName: function() {
    log(this.myName);
  }
};

obj.printName(); // "Mike"
runFunc(obj.printName); // undefined
runFunc(_.bind(obj.printName, obj)); // "Mike"
<pre></pre>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91