Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Created November 11, 2019 00:03
Show Gist options
  • Save sam-ngu/ae18d4965357f0e79b9689d6c2a39f1c to your computer and use it in GitHub Desktop.
Save sam-ngu/ae18d4965357f0e79b9689d6c2a39f1c to your computer and use it in GitHub Desktop.
JS arrow function demonstration
let clock = {
timerIntervalId: null,
timer: 60, // 60 sec
startTimer: function(){
//
function decrement(){
if(this.timer < 0)
this.stopTimer()
else
this.timer -= 1
}
// this wouldn't work. By default, the closure "decrement" is not bound to the current clock object,
// so the "this" keyword in the closure is referred to the "window" object,
// ie, it won't be able to access the "timer" property and "stopTimer" method
this.timerIntervalId = setInterval(decrement, 1000);
// To make the "this" keyword refer to the "clock" object, we will need to bind the closure
// to the current context as followed.
// Now the "this" keyword in the closure is bound to the current context, ie the clock object
this.timerIntervalId = setInterval(decrement.bind(this), 1000);
},
stopTimer: function () {
clearInterval(this.timerIntervalId)
}
}
let clock2 = {
timerIntervalId: null,
timer: 60, // 60 sec
startTimer: function () {
//
let decrement = () => {
if (this.timer < 0)
this.stopTimer()
else
this.timer -= 1
}
// Works without binding anything!
// The arrow function automatically bind the immediate context to itself.
this.timerIntervalId = setInterval(decrement, 1000);
},
stopTimer: function () {
clearInterval(this.timerIntervalId)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment