函数内部的iife需要明确地进行此分配

时间:2018-12-18 13:33:03

标签: javascript this

我已经在函数内部执行了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语法创建的对象。我怎么必须明确地通过它?

0 个答案:

没有答案