Last active
September 15, 2022 17:49
-
-
Save gowthm/5064e751c4ab62a1dfe358f2e4504fe3 to your computer and use it in GitHub Desktop.
Arrow function and different between regular 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
// 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