0

const func = (() => {
  
  const init = (data) => {
    organizeData(data);
    return this;
  }
  
  const otherFunc = () => {
    //Do something else
  }

  return {
  init:init,
  otherFunc: otherFunc
  }

})();

func.init(data).otherFunc()

I have an issue with the "this" in my init function. It refers to the window instead of my func object.

it returns func.init(data).otherFunc() is not a function because it points to the window instead of my func

Thanks in advance

Nizar AYARI
  • 203
  • 2
  • 12

1 Answers1

0

The arrow function will assign the context of this to the same context in which it was defined not when it was executed.

This means the first line in your example will bind this to the global namespace because it was defined in the global scope.

If you intend a function to be dynamically bound at run time you're forced to use the old function () {} version and not () => {}.

A good rule of thumb is to only use the arrow functions when you are inside a known context.

Sukima
  • 9,965
  • 3
  • 46
  • 60
  • There is not other way around to it except using es5 function ? – Nizar AYARI Oct 06 '16 at 21:57
  • @NizarAYARI: Arrow functions solve some very specific use cases. They are not a complete replacement for function declarations/expressions. – Felix Kling Oct 06 '16 at 22:00
  • 1
    @NizarAYARI It's not like function declaration are ES5 and arrow functions are ES6. Normal functions are and will continue to be an important part of the language, and you should not use arrow functions where you don't need them. In fact, you'll notice that function declarations are even simpler and shorter than what you currently have. – Bergi Oct 06 '16 at 22:13