3 ms·
You bind scope by setting the variable this to a locally scoped variable before your function call: var foo = { 'bar': function () { var that = this;
by seasoup 17y ago
You bind scope by setting the variable this to a locally scoped variable before your function call:
var foo = {
'bar': function () {
var that = this;
$(selector).each(function () {
alert(that);
}
}
}
or else in the cases of objects like the above where there is only one instance of the object you can refer to foo by name.
var foo = {
'bar': function () {
$(selector).each(function () {
alert(foo);
}
}
}
Events are a bit trickier as they get set on DOM elements and the variable declared in front of it with local scope cannot be accessed from within.
var foo = {
'bar': function () {
var that = this;
$(selector).click(function () {
alert(that); // doesn't work!
}
}
}
You can get around this by passing a variable into the function called by the event.
var foo = {
'bar': function () {
var that = this;
$(selector).bind('click', {'that': this}, function (e) {
alert(e.data.that); //accessed via e.data
}
}
}