2

How can I refer the 'real' this in an attached event handler using JavaScript OOP?

Is is the best practice to refer to the instance by using the local variable 'anyVariable'?

var myClass = (function () {
function myClass(gridId) {
    $(function () {
        // misc init code replaced here
        this.initKeyboard();
    });

}

myClass.prototype.initKeyboard = function () {
    var anyVariable = this; // keyword 'this' is clearly referring here to the instance
    $(document).keyup(function (e) {
        // I would like to refer here to the instance.
        // However it seems that the keyword 'this' refers here to the function (?)
        // Is is the best practice here to refer to the instance by using the local variable 'anyVariable'?
        anyVariable.myMember(...); //???
        }
    });
};
g.pickardou
  • 32,346
  • 36
  • 123
  • 268

1 Answers1

1

The usual variable name is self, that, or _this (see this question for more details), but yes, that's the usual way to keep the needed this value when the context changes

Community
  • 1
  • 1
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59