JavaScript >> Arrow function
function Foo() {
this.name = name;
this.count = 0;
this.startCounting();
}
Foo.prototype.startCounting = function() {
var self = this;
setInterval(function () {
// this is the Window, not Foo {}, as you might expect
console.log(this); // [object Window]
// that's why we reassign this to self before setInterval()
console.log(self.count);
self.count++;
},1000)
}
new Foo();
//Becomes
function Foo() {
this.name = name;
this.count = 0;
this.startCounting();
}
Foo.prototype.startCounting = function() {
setInterval(() => {
console.log(this); // [object Object]
console.log(this.count); // 1, 2, 3
this.count++;
},1000)
}
new Foo();
var foo = ['a', 'ab', 'abc'];
var bar = foo.map(f => f.length);
// Equivalent to
//function (f) {
// return f.length;
//}
console.log(bar); // 1,2,3