Skip to content

Instantly share code, notes, and snippets.

@zakmandhro
Last active January 17, 2022 16:45
Show Gist options
  • Save zakmandhro/ea980963ab85c4b07236c944a0405deb to your computer and use it in GitHub Desktop.
Save zakmandhro/ea980963ab85c4b07236c944a0405deb to your computer and use it in GitHub Desktop.
Show the difference in methods use to namespace functions in const
const WithFunc = {
description: "Hello",
classicFunction() {
console.log(this.description, "description") // works but can lead to 'this' confusion
return "classicFunction"
}
}
const WithConst = {
description: "Hello",
arrowFunction: () => {
console.log(WithConst.description, "description") // need to reference const
return "arrowFunction"
}
}
console.log(classicFunction()) // this works
function classicFunction() {
return "classicFunction"
}
// this doesn't works; const not initialized yet
// console.log(arrowFunction())
// but this works fine because when it's called, arrowFunction is initialized
// this would be the case if this module was exported
const useArrowFunction = () => arrowFunction()
const arrowFunction = () => {
return "arrowFunction"
}
console.log(useArrowFunction())
@zakmandhro
Copy link
Author

You can try this code out on typescriptlang.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment