Skip to content

Instantly share code, notes, and snippets.

@ygweric
Last active January 29, 2018 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygweric/422cee5dbd7e79dd6fa94da561e8ae50 to your computer and use it in GitHub Desktop.
Save ygweric/422cee5dbd7e79dd6fa94da561e8ae50 to your computer and use it in GitHub Desktop.
JavaScript 'this' and '=>' arrow function
const Adder = new function() {
this.sum = 0;
this.add = function(numbers) {
numbers.forEach(function(n) {
this.sum +=n;
});
};
}
Adder.add([1, 2, 3]);
console.log(`sum is ${Adder.sum}`); //"sum is 0"
const Adder2 = new function() {
this.sum = 0;
this.add = function(numbers) {
numbers.forEach(n => {
this.sum +=n;
});
};
}
Adder2.add([1, 2, 3]);
console.log(`sum is ${Adder2.sum}`); //"sum is 6"
const Adder3 = new function() {
this.sum = 0;
this.add = function(numbers) {
numbers.forEach(function(n) {
this.sum +=n;
}.bind(this));
};
}
Adder3.add([1, 2, 3]);
console.log(`sum is ${Adder3.sum}`); //"sum is 6"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment