Marley Marley - 1 month ago 9
Javascript Question

How to pass a self invoking function as a function argument in JavaScript?

I have the following code where I am using the arrow functions to get my work done. This works perfectly in Chrome and Firefox as they support arrow functions.

this._subscription = this._modal.shown.subscribe(() => this._el.nativeElement.focus());


But, this doesn't work properly in IE 11. So, I am trying to convert this arrow function into an anonymous self invoking function. I did the following:

this._subscription = this._modal.shown.subscribe((function(){ this._el.nativeElement.focus()})());


But the above code isn't working. Am I doing something wrong? How can I do this. Any suggestions and help would be appreciated.

Answer

Do this:

this._subscription = this._modal.shown.subscribe((function(){ this._el.nativeElement.focus();}).bind(this));

Here, as @harmic mentioned in the above answer's comment, this would no longer be referencing the previous value, as the scope changes in this case. So, you got to bind this to make it work.