Javascript question about "this" in function(){}

var self=this
this.content.getComponent(cc.Animation).scheduleOnce(function(event){

           self.content.getComponent(cc.Animation).play();

        },3);

in this code why is the self variable crucial? why cant i just use this?

Because in JS function has its own this, so if you want to have “higher” this you should save it in variable as in code you provided.

You also can use arrow functions to solve this issue, arrow functions haven’t own this:

this.content.getComponent(cc.Animation).scheduleOnce((event) => {
    this.content.getComponent(cc.Animation).play();
},3);
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.