Some tip about "this pointer" in JS

Continuing the discussion from Cocos2d-JS Game Competition - INCOMPLETE Game:

I post an example here:

cc.eventManager.addListener(
{

onTouchesBegan:function(touch,event)
{
this.test();
}
}

It will throw a TypeError: this.test is not a function when I dispatch this event, so I guess it is because of the difference of the “this pointer” when I step into the callback.

So generally, my solution is to pass a parameter to the callback to tell the callback function “this pointer”. I think there should be some better solutions.

Hi, in fact, the this object is the reference of the listener, and if you want the outer scope this, you can do something like this:

cc.eventManager.addListener(
{
.....
    onTouchesBegan:function(touch,event)
    {
        var outerThis = event.getCurrentTarget();
        outerThis.test();
    }
}, this); // The this here will be passed with event

Refer to the document of event manger here: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/eventManager/en

In general, the callback functions’ this doesn’t refer to the outer this in javascript, there is no rule, it depend on how the callback is invoked, please search JavaScript variable scope and context for more informations

Ok thanks very much I will check it :wink:

I have read this article:

If we want the callback know the “this” context, we need to do sth like

function MyClass(){
this.element = document.createElement(‘div’);
this.element.addEventListener(‘click’, this.onClick.bind(this), false);
}

MyClass.prototype.onClick = function(e){
// do something
};

which is quite useful solution for me

Yes, the bind solution works also, thanks for the tip

:wink: you are welcome