0

Is there a way to call inc of obj without bind?

 function callIt(callback){
   callback();
 }

 var obj = {
    count: 0,
    inc: function(){
       this.count++;
    }
 };

 callIt(obj.inc.bind(obj));
 obj.count;// 1

Question is relevant to me because of older IE-versions that do not support the method bind.

Blauharley
  • 4,186
  • 6
  • 28
  • 47
  • 2
    Have a look at [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) for alternative solutions. – Felix Kling Feb 20 '14 at 17:39
  • 1
    My recommendation is to use [`es5-shim.js`](https://github.com/es-shims/es5-shim) (or equivalent) and move on with more interesting problems. Alternatively, a shim/polyfill can be found in [MDN's Function.bind documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – user2864740 Feb 20 '14 at 17:40
  • That is a related source with interesting answers to this topic: http://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function – Blauharley Feb 22 '14 at 18:39

1 Answers1

1

You could use a function value

callIt(function() { obj.inc(); });
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454