【发布时间】:2012-11-24 00:13:46
【问题描述】:
我目前正在为我正在开发的游戏编写一个类,该类根据页面 URL 中的哈希更改来控制应用程序路由。
我的问题是在将主路由函数附加到 hashchange 事件后,“this”的上下文变为“window”。
这是目前为止的代码:
Game.Router = function() {
return {
init: function() {
window.addEventListener('hashchange', this.route, false);
},
route: function(e) {
e.preventDefault();
var routingLocation = e.newURL.substr(e.newURL.indexOf('#!/') + 3, e.newURL.length);
switch(routingLocation) {
case "new":
this.toggleView('Game');
break;
case "instructions":
this.toggleView('Instructions');
break;
case "scores":
this.toggleView('Scores');
break;
case "about":
this.toggleView('About');
break;
}
},
toggleView: function(viewID) {
var els = document.querySelectorAll('section');
for(var i=0, l=els.length; i<l; i++) {
if(els[i].id == viewID) {
els[i].className = 'currentGameSection';
} else {
els[i].className = '';
}
}
}
}
}();
当我尝试在路由函数的 switch 语句中调用 this.toggleView 时,结果发现“this”已从 Game.Router 更改为 window。问题可以通过将 this.toggleView 替换为 Game.Router.toggleView 来解决,但这并不理想。
有人可以帮我理解为什么添加事件侦听器后“this”上下文会发生变化吗?
【问题讨论】:
-
这是关于 SO 最重复的问题之一。我建议您阅读以下内容,而不是寻找完全相同的副本:stackoverflow.com/questions/1085674/…
-
是的,我有一种感觉。搜索结果没有任何用处......
标签: javascript