4 ms·
If you're writing OO javascript, you often want to use "this" to refer to your object, but various things in js and especially jquery can change the meaning/sco
by jontas 13y ago
If you're writing OO javascript, you often want to use "this" to refer to your object, but various things in js and especially jquery can change the meaning/scoping of "this". So for example, if you have:
var myObj = {
foo: 'bar',
baz: function() {
console.log(this.foo); //would give you 'bar', as expected
//but if you have some code that changes the meaning of this, for example:
$('.button').click(function() {
console.log(this.foo); //undefined, since now "this" refers to the scope of the event's callback function
});
//but if you use bind:
$('.button').click((function() {
//now "this" is scoped to refer to the main object
console.log(this.foo); //gives you 'bar'
}).bind(this));
}
}