DEV Community

Discussion on: Emulating "Private" Variables in JavaScript with Closures and Factory Functions

Collapse
 
denik1981 profile image
denik1981
const privates = new WeakMap()
class Animal {
  constructor(name, job) {
    privates.set(this, { name, job })
    console.log('I'm a total GENIUS!')
  }
}
// A few lines later on the code ....
function privates() {
  console.log("No, you are not. Do you remember the NO-GLOBALS rules?")
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
qm3ster profile image
Mihail Malo

1. Uncaught SyntaxError: missing ) after argument list

You would have caught this one if you used highlighting:

const privates = new WeakMap()
class Animal {
  constructor(name, job) {
    privates.set(this, { name, job })
    console.log('I'm a total GENIUS!')
  }
}
// A few lines later on the code ....
function privates() {
  console.log("No, you are not. Do you remember the NO-GLOBALS rules?")
}
Enter fullscreen mode Exit fullscreen mode

vs

const privates = new WeakMap()
class Animal {
  constructor(name, job) {
    privates.set(this, { name, job })
    console.log("I'm a total GENIUS!")
  }
}
// A few lines later on the code ....
function privates() {
  console.log("No, you are not. Do you remember the NO-GLOBALS rules?")
}
Enter fullscreen mode Exit fullscreen mode

2. Uncaught SyntaxError: Identifier 'privates' has already been declared (pointing at the function, not the const)

Have you forgotten declaration collision? (TypeScript would also have caught it statically)

3. "globals" are fine when you are thinking in modules