代码之家  ›  专栏  ›  技术社区  ›  potato

函数内部的IIFE需要显式的此赋值[重复]

  •  0
  • potato  · 技术社区  · 6 年前

    我在一个函数中执行了一个生命。我很惊讶 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
    

    在生命的召唤点上, 指向使用 new 语法。为什么我要明确地通过呢?

    0 回复  |  直到 6 年前