0

I've executed an IIFE inside a function. I was surprised that this inside IIFE does not show to the this that was passed when the function was called. Take a look at this code:

function Music(){
    this.musicFolderPath;

    (function() {
        if (comecheck)) {
            this.musicFolderPath = "value2"; // never gets assigned to the correct this.musicFolderPath
        }
    });

}

var music = new Music();
//music.musicFolderPath is undefined

However, if apply is used, than it is no problem:

function Music(){
    this.musicFolderPath;

    (function() {
        if (comecheck)) {
            this.musicFolderPath = "value2"; // never gets assigned to the correct this.musicFolderPath
        }
    }.apply(this));

}
var music = new Music();
//music.musicFolderPath is assigned correctly

At the point of iife call, this points to the object that was created using new syntax. How come I have to pass it explicitly?

potato
  • 4,143
  • 2
  • 32
  • 88
  • aah, I missed another pair of braces. stupid me – potato Dec 18 '18 at 13:35
  • @quirimmo That will execute the function, but it *won't* be the "correct" `this`! – deceze Dec 18 '18 at 13:35
  • Might be able to just use a ternary `this.musicFolderPath = comecheck ? "value2" : undefined;` and not worry about setting this inside an IIFE. Or maybe even just: `this.musicFolderPath; if (comecheck) this.musicFolderPath = 'value2';` – Shilly Dec 18 '18 at 13:37
  • @deceze okay, can you tell me why? because I though I should work. – potato Dec 18 '18 at 13:38
  • @deceze yeah totally right, was just watching that the inner function is not executed at all, but the context is anyway different if you don't bind with the `this` – quirimmo Dec 18 '18 at 13:38
  • @Shilly I reverted to not using iife at all, but still posted the quetsion because it was bugging me. – potato Dec 18 '18 at 13:38
  • Read the duplicate. That's how `this` works. The way you call the function determines what it is. – deceze Dec 18 '18 at 13:39
  • hmm.. I guess I misinterpreted default this assignement. I thought that by default, whatever is assigned to be  `this` at the time of function execution, gets passed as `this` to the function. In this case, default `this` should be the one having `musicFolderPath` property. – potato Dec 18 '18 at 13:44

0 Answers0