Skip to content

Instantly share code, notes, and snippets.

@loganwoolf
Last active December 31, 2021 06:52
Show Gist options
  • Save loganwoolf/881a756d379e5fe1f0fd9bafa06f1f29 to your computer and use it in GitHub Desktop.
Save loganwoolf/881a756d379e5fe1f0fd9bafa06f1f29 to your computer and use it in GitHub Desktop.
Closure return value question
'use strict'
// reference
// https://www.telerik.com/amp/demystifying-closures-javascript/WEx1ZE1sRUVUWkE5S0dNbEhBNXJyUkU3T1Q4PQ2
const outer = ( () => {
let privateValue = ''
function setVar (str) {
privateValue = str
return privateValue
}
return {
// Why use one method over another?
// Method 1
// Explicity states required parameters,
// don't have to scroll back.
set1: (value) => setVar(value),
// Method 2
// Looks very clean and nice, why wouldn't
// you just name the function set2?
set2: setVar,
// Method 3
setVar
}
} ) ()
console.log(
outer.set1('success!'),
outer.set2('another success!'),
outer.setVar('a massive success!')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment