Javascript cocos2d js将精灵对象传递到EventListener

Javascript cocos2d js将精灵对象传递到EventListener,javascript,cocos2d-js,Javascript,Cocos2d Js,我正在使用cocos2djsv3.0,我正在尝试在EventListener中使用this.sprite对象。但是我知道this.sprite是未定义的 var roomMap = cc.Layer.extend({ sprite:null ctor:function(){ this._super(); this.init(); }, init: function () { this._super(); //create tile map this

我正在使用cocos2djsv3.0,我正在尝试在EventListener中使用this.sprite对象。但是我知道this.sprite是未定义的

var roomMap = cc.Layer.extend({

sprite:null


ctor:function(){
    this._super();
    this.init();
},

init: function () {
    this._super();
    //create tile map
    this.mainMap = cc.TMXTiledMap.create(res.Main_tmx);

    var cache = cc.spriteFrameCache;
    cache.addSpriteFrames(res.player_plist, res.player_png);

    this.sprite = new cc.Sprite.create("#player-stand-f-0");
    this.sprite.setPosition(new cc.Point(300,300));
    this.addChild(this.sprite);

    var listener = cc.EventListener.create({

        event: cc.EventListener.MOUSE,

        onMouseUp: function (event){
            var sprite_action = cc.MoveTo(2,cc.p(event.getLocationX(),event.getLocationY()));
            console.log(this.sprite);
            //this.sprite.runAction(sprite_action);
            //this.addChild(sprite_action);

        }
    });

    cc.eventManager.addListener(listener, this.sprite);
如果我在init函数中创建变量sprite并只传递sprite,它就可以正常工作。但是当我在init函数外创建var sprite并使用this.sprite时,我得到了未定义的

var roomMap = cc.Layer.extend({

sprite:null


ctor:function(){
    this._super();
    this.init();
},

init: function () {
    this._super();
    //create tile map
    this.mainMap = cc.TMXTiledMap.create(res.Main_tmx);

    var cache = cc.spriteFrameCache;
    cache.addSpriteFrames(res.player_plist, res.player_png);

    this.sprite = new cc.Sprite.create("#player-stand-f-0");
    this.sprite.setPosition(new cc.Point(300,300));
    this.addChild(this.sprite);

    var listener = cc.EventListener.create({

        event: cc.EventListener.MOUSE,

        onMouseUp: function (event){
            var sprite_action = cc.MoveTo(2,cc.p(event.getLocationX(),event.getLocationY()));
            console.log(this.sprite);
            //this.sprite.runAction(sprite_action);
            //this.addChild(sprite_action);

        }
    });

    cc.eventManager.addListener(listener, this.sprite);

这更像是我遇到的javascript问题。

首先,我认为这一行是错误的

this.sprite = new cc.Sprite.create("#player-stand-f-0");
“新”是不必要的

当你说“在init函数之外”时,我不知道它在哪里。 因为将首先调用ctor函数,一旦在使用之前没有创建它,它将是未定义的。你可以试试

sprite:cc.Sprite.create("player-stand-f-0")

之所以发生这种情况,是因为事件监听器内部的
这个
,指的是事件监听器本身,而不是层

试试这个:

var target = event.getCurrentTarget();
console.log(target);
console.log(target.sprite);
这应该让您清楚地了解发生了什么:如果您正在单击精灵对象,则
目标
应等于
精灵
(因此
目标。精灵
将是未定义的),如果您正在单击层,则
目标
将是该层,而且
target.sprite
将是您所期望的


为了进一步了解cocos2d v3中新的事件管理器,我建议大家看一看。

谢谢您的文章。是目标现在有图层对象。