Skip to content

Instantly share code, notes, and snippets.

@gowthm
Last active September 15, 2022 17:49
Show Gist options
  • Save gowthm/5064e751c4ab62a1dfe358f2e4504fe3 to your computer and use it in GitHub Desktop.
Save gowthm/5064e751c4ab62a1dfe358f2e4504fe3 to your computer and use it in GitHub Desktop.
Arrow function and different between regular function
// Regular Function with "this"
function Car() {
this.speed = 0;
this.speedUp = function(speed) {
this.speed = speed;
// let self = this; ----> without line anonymous function take as shadow from speedUp function.
setTimeout(function () {
console.log(self.speed)
}, 100)
}
}
let car = new Car();
console.log(car.speedUp(20));
// Arrow Function with 'this'
// an arrow function captures the this value of the enclosing context instead of creating its own this context
function Car() {
this.speed = 0;
this.speedUp = function(speed) {
this.speed = speed;
setTimeout(() => {
console.log(this.speed)
})
}
}
let car = new Car();
console.log(car.speedUp(20));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment