[英]Closure returning undefined unexpectedly
我正在創建一個melonJS游戲。
在我的玩家實體中game.PlayerEntity = me.ObjectEntity.extend({
,其更新功能檢查碰撞:
game.PlayerEntity = me.ObjectEntity.extend({
var collision = me.game.collide(this);
if (collision) {
if (collision.obj.type == me.game.ACTION_OBJECT) {
console.log("NPCname: " + game.NPCEntity.init); //get settings from NPCEntity
}
}
然后在我的NPC實體對象中game.NPCEntity = me.ObjectEntity.extend ({
,我想將settings.name
返回給上面的PlayerEntity。為此,我創建了一個閉包returnSettings()
。
1) console.log(settings.name)
按預期輸出“ Lee”
2) return settings.name
輸出“未定義”
為什么是這樣?
game.NPCEntity = me.ObjectEntity.extend ({
init : function(x, y, settings) {
settings.image = "wheelie_right";
settings.spritewidth = 64;
settings.name = "Lee";
this.parent(x, y, settings);
this.collidable = true;
this.type = me.game.ACTION_OBJECT;
console.log(settings.name); //works
console.log("returning... " + returnSettings()); //works
//closure to return settings values externally
function returnSettings () {
return settings.name; //returns undefined when called by PlayerEntity above.
}
},
謝謝!
game.NPCEnity
不引用實例,而是構造函數。 如果在構造函數中設置this.settings = …
,則將在instance上創建一個屬性。 您可以在update
函數中使用this
關鍵字訪問實例,在this
實例中您可以處理碰撞,並且它確實指向player
。
引用本教程:
// call by the engine when colliding with another object // obj parameter corresponds to the other object (typically the player) touching this one onCollision: function(res, obj) {…}
這意味着您可以通過該事件處理程序中的obj.settings
訪問敵人設置。
如果您不使用該處理程序而是調用collide
方法 ,那么從我看到的結果來看,該函數的返回值具有.obj
屬性,這大概是碰撞目標:
if (collision) {
if (collision.obj.type == me.game.ACTION_OBJECT) {
console.log("NPCname: " + collision.obj.settings.name); //get settings from NPCEntity
}
}
顯然,您可以在定義函數之前調用該函數,因為它是以函數名(){}的形式而不是表達式來定義的: https : //stackoverflow.com/a/261682/880114
但是我看不到您在哪里返回該函數以從其他地方調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.