Created
September 5, 2018 07:50
-
-
Save isaac-weisberg/dd4d5a153d21ab9d8bcbb8d20824c6a8 to your computer and use it in GitHub Desktop.
This a typescript file that explains the difference between an arrow function and a named function in Javascript runtime
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 l = console.log | |
class Asdf { | |
memberProp = 3450 | |
methodA = () => { | |
const a = this.memberProp | |
return a | |
} | |
methodB() { | |
const a = this.memberProp | |
return a | |
} | |
constructor() { | |
const objWithArrow = { | |
meth: this.methodA | |
} | |
const objWithFunction = { | |
meth: this.methodB | |
} | |
const objWithArrowResult = objWithArrow.meth() | |
l(objWithArrowResult) // Prints 3450 | |
const objWithFunctionResult = objWithFunction.meth() | |
l(objWithFunctionResult) // Prints `undefined` because this is not *lexical*. | |
// Once a named (or anonymous) function is assigned to a property of | |
// an object, its `this` is exchanged for that assignee. | |
// Arrow functions, however, maintain their `this` value. | |
/* | |
Could've declared as | |
const objWithFunction = { | |
meth: this.methodB, | |
memberProp: 3450 | |
} | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment