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));
}
}
Re:Fat arrow functions in Javascript
by armandososa on Friday September 20, 2013 @01:56PM
(#6419362)
this is a good start http://yehudakatz.com/2011/08/11/understanding-javascript-fu...
Great link, that really clarified things for me (I think). The OP article uses this sample as something you can do with fat arrows. "Because the containing scope closes over the fat arrow function, you can do things like,"
let fib = (n) => {
if (n <= 1) return 1;
return fib(n - 1) + fib(n - 2};
}
I don't understand what this is showing. Wouldn't this code work the same way without fat arrows because there's no `this` being used anywhere?You can use Function.prototype.bind instead of creating a closure. Check out the examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
In other words, what do I need to read before I can understand this article?