函数未定义-不明白为什么
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
相关文章:
- 可以'我不明白为什么;t将行和单元格添加到表中
- Don'我不明白为什么我的setInterval+jQuery;不起作用
- 我可以'我不明白为什么我能;不要在JavaScript中更改蜡笔的颜色
- 意外;在我的JavaScript中,我不明白为什么
- 编程新手,可以'我不明白为什么这个因子计算器没有;不起作用
- 不明白为什么我不用我的脚本更改我的 PHP 变量
- 我不明白为什么轮播中的幻灯片不可见
- 我不明白为什么我的代码不获取输入框的值并创建一个新对象
- 不明白为什么 Backbone collection.create 不发布数组
- 不明白为什么我的 CSS 不起作用
- 骨干.js事件没有开火,我不明白为什么
- 不明白为什么不应该在语句的开头使用对象文字
- 我没有'我不明白为什么;这个“;关键字dons'I don’我没有预料到的那么管用
- Don'我不明白为什么这个JavaScript函数可以用一种方法调用,而不能用另一种方法
- 我的json对象变成null,我可以'我不明白为什么
- 可以'我不明白为什么;不要给我任何输出值
- 可以'我不明白为什么我的JS;不起作用
- 不明白为什么我的选择不会总结
- 我可以'我不明白为什么得分不高;我不在玩石头、布、剪刀的游戏
- Javascript方法崩溃了——我只是不明白为什么