Search code examples
javascriptkineticjs

this inside callback function


Here is my situation.

function Bird() {
  this._canFly = true;
  this._legs = 2;
  this._flying = false;
}

Bird.prototype = {
  Fly: function() {
    if ( this.canFly ) {
        layer.on('fly', function() {
           this.setStrokeWidth(4); //this refers to layer(kinetic.js) object
           this._flying = true; //this refers to Bird object
        });
    }//end if
  } //end function
);

Here I need to access both layer object and bird object inside the callback function. Can somebody tell me how to handle the above situation ?


Solution

  • var self = this
    

    Cache a reference to this to refer to it when it changes context.