函数未定义-不明白为什么

function undefined - don't understand why

本文关键字:明白 为什么 未定义 函数      更新时间:2023-09-26

我有两个同名的函数,但我认为它们是本地化的,所以我不确定我在这里不理解什么,似乎其中一个函数没有创建或什么。

我的代码设置是这样的-它从底线开始:

function getDiv(id)    {
    return document.getElementById(id);
}

var account = new function(){
    this.load = function(){     
        //load user data from server to elements
    }

    this.init = function(){
        this.load(); //ERROR : this.load is not a function
    }
}
var template = new function(){    
    this.addEvents = function(){ 
         var el = getDiv('output');
         el.addEventListener('mousedown',account.init,false);
    }
    this.load = function(){ 
        //load template to page
        this.addEvents();
    }

    this.init = function(){
        this.load();
    }
}
template.init(); //start of the script: load template

我希望它有合理的意义在以下代码去,但我不明白为什么在account.init我得到一个错误,但对于template.init我没有-他们是非常相似的设置。

是什么原因导致的,我该如何解决它?

事件监听器在this中调用的值与在它们被添加的上下文中调用的值不同。

要设置所使用的this的值,可以使用bind函数:

el.addEventListener('mousedown', account.init.bind(account), false);

在创建事件侦听器el.addEventListener('mousedown',account.init,false);时,元素el成为account.init的作用域,这就是this将引用的地方。为了避免这种情况,将对this的引用保存为闭包。

var account = new function(){
    var self = this;
    this.load = function(){     
        //load user data from server to elements
    }
    this.init = function(){
        self.load(); // "this" as in "account" is accessible here through the closure "self"
    }
}

this和闭包信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this