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?