Last active
January 17, 2022 16:45
-
-
Save zakmandhro/ea980963ab85c4b07236c944a0405deb to your computer and use it in GitHub Desktop.
Show the difference in methods use to namespace functions in const
This file contains hidden or 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 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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One advantage of using
function
on line 19 is that it gets hoisted to top. A forward reference will work:The same will not work for const arrow function:
However, if arrowFunction is called from another const or function (which is typically how you'd do it) then it's fine.