1

What's the difference in calling a function in these two cases?

var doSomething = function( doSomethingElse ) {
  // Some great things here before the doSomethingElse function call
  doSomethingElse();
}

// 1. case
var _this = this;
doSomething( function () {
  _this.doSomethingElse();
});

// 2. case
doSomething( this.doSomethingElse );

In the first case it will find the doSomethingElse properly. The second case does not work as expected.

Thanks!

cor
  • 3,323
  • 25
  • 46
Tuomas
  • 11
  • 1
  • Where have you defined `doSomethingElse`? – sabithpocker Mar 22 '17 at 10:05
  • I guess you're looking for [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). `doSomething( this.doSomethingElse.bind(this));` should work – hindmost Mar 22 '17 at 10:07
  • It should work as expected. I even tried both cases and they do work properly. Maybe you could verify again. – swathis Mar 22 '17 at 10:09
  • @swathis Ok, I could add the further complexity around it. Should I edit directly the question? The unexpected part is the variable "this" inside "this.doSomethingElse". The doSomethingElse function has a sibling function that is called inside it. That sibling function cannot be found in the 2nd case. Sorry. It's surprisingly complex to explain. – Tuomas Mar 22 '17 at 10:21
  • @hindmost I'm not sure what bind does at this moment. I have to look into it. Thanks! – Tuomas Mar 22 '17 at 10:23

0 Answers0