Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript传递到对象方法中_Javascript - Fatal编程技术网

javascript传递到对象方法中

javascript传递到对象方法中,javascript,Javascript,我正在调用一个方法,并希望使用this引用该方法之外的对象精灵 调用这个in对象只会给出传入的事件对象。我正在尝试访问moveSprite:函数中的this.sprite var roomMap = cc.Layer.extend({ sprite:null, listener:null, ctor:function(){ this._super(); this.init(); }, init: function ()

我正在调用一个方法,并希望使用this引用该方法之外的对象精灵

调用这个in对象只会给出传入的事件对象。我正在尝试访问moveSprite:函数中的this.sprite

var roomMap = cc.Layer.extend({
    sprite:null,
    listener:null,

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

    init: function () {
        this._super();

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

        this.listener = cc.EventListener.create({

            onMouseDown: function(event) {
                cc.log("onMouseDown");
            },
            onMouseUp: this.moveSprite
        });

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

        return this;

    },

    moveSprite:function(event){
        cc.log("mouse up: "+event.getLocationX() + "mouse move: "+event.getLocationY());
        console.log(this);
        var sprite_action = cc.MoveTo(2,cc.p(event.getLocationX(),event.getLocationY()));
        this.sprite.runAction(sprite_action);
        this.addChild(sprite_action);
    }

}))

除非您的
cc
库为您提供了具体的方法,否则通常的方法是使用ES5的
功能#bind
(可以在旧发动机上填充):

Function#bind
返回一个函数,该函数在调用时将调用原始函数,并将
this
设置为您给出的第一个参数
bind
。(您还可以提供
bind
更多参数,这些参数将作为初始参数传递给原始函数,然后是调用
bind
返回的“绑定”函数时提供的任何参数。)


因此,在上面的一行中,我们说“创建并返回一个函数,当调用该函数时,它将调用
moveSprite
,并将
this
设置为当前的
this
,并将其分配给
onMouseUp
属性。”

是否
cc.eventManager.addListener
看起来像是设置了
这个
?@JuanMendes:嗯,OP建议没有发生这种情况,所以。。。但我同意,只是看看,这就是我读这句话的方式,是的。如果知道
cc
lib是什么,那就太好了。cc lib是cocos2d-js@JuanMendes:奇怪的是,
addListener
似乎没有使用第二个参数(但我同意它看起来是这样的):“您可以通过
addListener
将侦听器添加到
cc.eventManager
addListener
支持两个参数:
listener
nodeOrPriority
,如果
nodeOrPriority
cc.Node
cc.Node
的子类对象,它将作为
SceneGraphPriority
添加侦听器。”,如果
nodeOrPriority
是数字值,它会将侦听器添加为
FixedPriority
“您应该解释您使用的库是什么。文档在哪里?@JuanMendes:例如:
onMouseUp: this.moveSprite.bind(this)