[英]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.