簡體   English   中英

函數未定義-不明白為什么

[英]function undefined - don't understand why

我有兩個同名的函數,但我認為它們已本地化,所以我不確定在這里我不明白的地方,似乎其中一個函數未創建或類似的東西。

我有這樣的代碼設置-它從底線開始:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM