Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Created September 5, 2018 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaac-weisberg/dd4d5a153d21ab9d8bcbb8d20824c6a8 to your computer and use it in GitHub Desktop.
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
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