Last active
January 29, 2018 02:24
-
-
Save ygweric/422cee5dbd7e79dd6fa94da561e8ae50 to your computer and use it in GitHub Desktop.
JavaScript 'this' and '=>' arrow function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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