【已解决】有关this.getChildByTag()的使用问题,求教。

var Sprite1=new cc.Sprite(res.Sprite1_png);
        //Sprite1.name="Sprite_1";
        Sprite1.setPositionX(150);
        Sprite1.setPositionY(150);
        this.addChild(Sprite1,2,SP_TAG);


```

这是ctor里定义的一个精灵
onKeyPressed: function (keyCode,event){
                cc.log(keyCode + "Pressed");
                {
                    var spritee = this.getChildByTag(SP_TAG);
                    switch(keyCode){
                        case 37:{
                            if (spritee.getPositionX()>=150)
                                spritee.runAction(cc.moveBy(2,cc.p(-100,0)));
                            else
                                spritee.runAction(cc.moveTo(2,cc.p(50,spritee.getPositionY())));

                        }
                            break;
                        /*case 38:{
                            if (sprite.)
                        }*/
                        default:
                            break;

                    }
                }
            }


```


这是onEnter里定义的键盘事件,然后
 var spritee = this.getChildByTag(SP_TAG);


```
这一句在浏览器里会报错:Uncaught TypeError: this.getChildByTag is not a function
难道这个函数不可用?

说明一下:SP_TAG是我定义的一个常量,一个整数;
关于getChildByTag的用法我模仿的书里的,不造对不对。

你需要确定的是,你this指向的是哪个对象。就这个来看,估计指向了window。

第一个精灵是放在层的ctor里的;
第二个键盘事件是放在层的onEnter里的;

我理解的,this应该是那个层。

this谁调用,指向谁,你可以在onKeyPressed,跟踪下this的

你理解得不对。。。

我好像明白了,键盘事件中的this或者parent应该不能映射到菜单、精灵这些类,对吗?
我把代码改了下,那里就不报错了

onEnter:function () {
this._super();
cc.log(“onEnter succeed!”);
var spritee = this.getChildByTag(SP_TAG);

    cc.eventManager.addListener({
        event:cc.EventListener.KEYBOARD,
        onKeyPressed: function (keyCode,event){
            cc.log(keyCode + "Pressed");
            {

                switch(keyCode){


把spritee的声明放到了键盘监听事件的外面就好啦! :875:谢谢各位!