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