0

Have a loop, there i have a instance which I will sometime set a method eqvialent to a object which change something in that object. But when I try, it says it is undefined.

var a = [];
a.push(
 {
  x:0
  func: function(){this.x++; console.log(this.x);}
 }
);

doFuncInLoop = a[0].func;
doFuncInLoop();

The console log will say this.x i undefined and I understand it not refer to the object, it refer to doFuncInLoop.x, but I want it to change a[0].x

Allan
  • 92
  • 7
  • It's losing it's calling context because you're calling it as a standalone function. Call the function with the calling context of the object instead – CertainPerformance May 07 '19 at 06:49
  • 1
    In case it's not clear, just do `a[0].func();` –  May 07 '19 at 06:53
  • Found this with bind, which solve my problem. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Allan May 07 '19 at 09:14

0 Answers0