The values in the assigned function bear no relation to the values outside of the function.
This code:
Code:
this.listen = function() {
alert("I'm listening! "+this.ele.attr('id'));
};
does the same as this code:
Code:
function listenHandler() {
alert("I'm listening! "+this.ele.attr('id'));
};
this.listen = listenHandler;
Now it's easier to tell that the function only knows about the variables at the time the function is called.
What you can do about that is to invoke a function and pass that variable to it. When you then return a function from inside that invoked one, the returned function retains knowledge of the passed variable.
Code:
function listenHandler() {
alert("I'm listening! "+ele.attr('id'));
};
this.listen = function (ele) {
return listenHandler;
}(this.ele);
You can then condense that down to the following:
Code:
this.listen = function (ele) {
return function () {
alert("I'm listening! "+ele.attr('id'));
};
}(this.ele);
Bookmarks