How to reference a function from JavaScript class method
Your class structure is perfectly valid. However, if your handleChange()
function uses the this
keyword, expecting someVar
, then that is where your problem lies.
This is what happens:
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange);
correctly references the handler function within the class. SWFAddress caches that function to some variablef
until the event is dispatched.- When the event is dispatched, SWFAddress calls
f
. While the reference to the function is preserved, the reference to the context, orthis
, is not. Thereforethis
defaults towindow
.
To get around this, you simply need to use an anonymous function that captures the variables within the class scope. You can call the handler with the correct context from within this anonymous function:
function SomeClass() {
this.initializeSWFA = function() {
// Save a reference to the object here
var me = this;
// Wrap handler in anonymous function
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function (evt) {
me.handleChange(evt);
});
}
// SWFAddress suppose to call this function
this.handleChange= function(evt) {
// Some code here
}
}
##An explanation of this
, as requested by the OP:##
The this
keyword can be explained in different ways: take a read of firstly this article about scope, and then this article about object-oriented JavaScript.
I'd like to throw in my quick reasoning too, which you may find helpful. Remember that JavaScript doesn't have "classes" as languages such as Java do. In those languages, a "method" of a class belongs only to that class (or could be inherited). In JavaScript however, there are only objects, and object properties, which can happen to functions. These functions are free agents -- they don't belong to one object or another, just like strings or numbers. For example:
var a = {
myMethod: function () {...}
};
var b = {};
b.myMethod = a.myMethod;
In this case, which object does myMethod
belong to? There is no answer; it could be either a
or b
. Therefore a.myMethod
is simply a reference to a function, disassociated from the "context", or parent object. Therefore this
has no meaning unless it is called explicitly using a.myMethod()
or b.myMethod()
, and thus defaults to window
when called in any other way. It is for the same reason that there is no such thing as a parent
or super
keyword in JavaScript.