我对JS特别是原型机很陌生。我有这个类,我不知道如何访问这些属性。
var Lobby = function (preloader, serverConn) {
// Hold a reference to EventBus
this.serverConn = serverConn;
this.preloader = preloader;
this.scheduleItemService = new ScheduledItemService(this.preloader);
this.stage = new createjs.Stage("lobbyCanvas");
};
Lobby.prototype.start = function(me, signedRequest) {
sendMessage(data, function() {
// inside this scope this.stage is undefined!
renderLobbyImages(this.stage, this.scheduleItemService);
});
};
function renderLobbyImages(stage, scheduleItemService) {
stage.update();
};呼叫代码:
var lobby = new Lobby(preloader, serverConn);
lobby.start(me, status.authResponse.signedRequest);我访问'renderLobbyImages‘做错了什么??
谢谢:-)
发布于 2015-12-22 18:11:28
在javascript中,this不是根据声明/使用的位置来解析的。当它被调用时就会被解析。(见:Javascript中的"this“关键字是如何在对象文字中起作用的?)。
因此,在上面的代码中,由于this是在对sendMessage()的回调中调用的,而且由于sendMessage是异步的(这意味着回调将在对start()的调用返回后很长时间内被调用),因此this是指全局对象(在web浏览器中是window,在node.js中没有命名)。
因此,实际上,您的代码正在执行此操作(没有双关语的意思):
sendMessage(data, function() {
renderLobbyImages(stage, scheduleItemService);
});由于没有名为stage或scheduleItemService的全局变量,因此两者实际上都是未定义的!
幸运的是,有一个解决办法。可以在闭包中捕获正确的对象:
var foo = this;
sendMessage(data, function() {
renderLobbyImages(foo.stage, foo.scheduleItemService);
});或者,您可以将正确的对象(this)传递给IIFE:
(function(x){
sendMessage(data, function() {
renderLobbyImages(x.stage, x.scheduleItemService);
});
})(this); // <-------- this is how we pass this或者:
sendMessage(data, (function(a){
return function(){
renderLobbyImages(a.stage, a.scheduleItemService);
}
})(this));或者在这种情况下,由于stage和scheduleItemService不是函数,您甚至可以直接传递它们:
sendMessage(data, (function(a,b){
return function(){
renderLobbyImages(a,b);
}
})(this.stage, this.scheduleItemService));这个问题有很多解决办法。就用你最舒服的那个。
https://stackoverflow.com/questions/34421190
复制相似问题