我已经在函数内部执行了IIFE。我很惊讶
IIFE中的this
不会显示给调用该函数时传递的this
。看一下这段代码:
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
但是,如果使用了apply,那就没问题了:
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
在调用iife时,this
指向使用new
语法创建的对象。我怎么必须明确地通过它?