簡體   English   中英

JS對象的異常行為

[英]JS Object odd behavior

我目前正在嘗試使用Phaser和Eureca io構建多人游戲。 我正處於嘗試對玩家及其身份進行身份驗證的階段,我正在服務器上使用具有返回正確玩家ID的方法的方式來進行此操作。

服務器上的方法是-

 eurecaServer.exports.getPlayer2Id = function(name , id)
 {

   if(name == "Fly" && id == player2id)
   {
     console.log("correct fly player");
     return player2id;
   }
   else
   {
     console.log("Wrong fly player");
     return id;
   }
}

目前在客戶端,我只是在測試,但是當我調用該函數時,它將返回一個對象。 當僅在控制台中查看對象時,它將顯示此內容。 Object {status: 0, result: null, error: null, sig: "eY0IjunQt7"}所以它告訴我我的結果為null,這很奇怪,但是在擴展時會得到。

Object {status: 0, result: null, error: null, sig: "eY0IjunQt7"} callback: function() error: null errorCallback: function() onReady: (fn, errorFn) result: "jVcZvzetc8AAK45NAAAH" sig: "eY0IjunQt7"

如您所見,當擴展結果時,結果不為null,而正是我在尋找的東西,我嘗試了JSON.stringify,但它給了我第一個結果,告訴我結果為null。

關於如何獲得實際結果或為什么這樣的任何想法。

謝謝。

編輯:

服務器的客戶端組件在主游戲文件中定義

var eurecaClientSetup = function() {

var eurecaClient = new Eureca.Client();

eurecaClient.ready(function (proxy) {
    eurecaServer = proxy;

});

然后在對象類中在這里調用它。

this.name = "Fly"
this.id = index;  //Passed in on object creation
this.currPlayer = eurecaServer.getPlayer2Id(this.name, this.id);
console.log(JSON.stringify(this.currPlayer));
console.log(this.currPlayer);

無論框架*如何,任何服務器操作都將是異步的。 一旦結果可用,不同的框架就具有不同的獲取結果的方法。 在Eureca.io中,似乎在服務器函數名稱之后使用了.onReady()調用。

換句話說,您需要做的是將客戶代碼更改為以下內容:

this.name = "Fly"
this.id = index;  //Passed in on object creation
var _this = this; // needed because "this" inside function below won't be the same
eurecaServer.getPlayer2Id(this.name, this.id).onReady(function (id) {
    _this.currPlayer = id;
    console.log(_this.currPlayer); // shows the right thing
    // do other stuff here now you have the right player id
});

*從技術上講,您可以執行同步/阻止AJAX請求,但是在99%的情況下,這是不正確的做法。

我是eureca.io的作者,GregL給出的答案是正確的。 我只想補充一下onReady()調用將被棄用,eureca.io支持像call這樣的承諾(使用then()函數)。

因此您可以改用這種語法,這是更標准的方法。

this.name = "Fly"
this.id = index;  //Passed in on object creation
var _this = this; // needed because "this" inside function below won't be the same
eurecaServer.getPlayer2Id(this.name, this.id).then(function (id) {
    _this.currPlayer = id;
    console.log(_this.currPlayer); // shows the right thing
    // do other stuff here now you have the right player id
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM