[英]JS prototype class with private methods not accessing properties
我是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”時我做錯了什么?
謝謝 :-)
在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));
有很多解決此問題的方法。 只需使用最舒適的一種即可。
兩個問題。
this
在scheduleItemService
的構造函數中丟失。
您調用的某些分配值的函數似乎未返回任何內容。
new createjs.Stage("lobbyCanvas"); new ScheduledItemService
您的調用方法還可以。
this
總是指調用對象。 當你說...
varlobby = new Lobby();
lobby.start();
...您的調用對象是lobby
,該lobby
具有start()
函數所需的所有字段。 但是初始化似乎無法正常工作。
請閱讀此MDN入門指南 。
在這個問題上,我們還將討論基於經典和基於原型的OOP。 有關我提到的教程的更多信息,請參見Paul S的答案 。 如果您需要以經典的OOP格式觀看教程,請參閱我的答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.