Reputation: 35822
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(...); //???
}
});
};
Upvotes: 2
Views: 39
Reputation: 10342
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
Upvotes: 1