0

In JavaScript, we have the concept of classes which is "syntactic sugar" for functions. My idea is that everything we can do with classes, we can also do with function constructors. Is this true? And if this is true, is there a way to create private fields with a function constructor?

For classes, private fields are declared using the hash symbol (#).

  • 1
    `Is this true?` No, classes are not merely syntactic sugar. There's a few things that classes do which can't be done with function constructors, with private fields being a prime example. – Nicholas Tower May 17 '22 at 14:36
  • 1
    You might be interested in [using WeakMaps](https://modernweb.com/private-variables-in-javascript-with-es6-weakmaps/). – kelsny May 17 '22 at 14:38
  • 1
    As mentioned, you can have something *pretty similar* with a WeakMap - it's not exactly the same, and requires more code, but does offer true privacy via a closure. – CertainPerformance May 17 '22 at 14:41
  • [Babel](https://babeljs.io/repl#?browsers=defaults%2C%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=false&corejs=3.21&spec=false&loose=false&code_lz=MYGwhgzhAEASCmIQHsDqyBOIAm0DeAUNMQBaIrQC80ATAAwDcRxAxAO6Y5XQCMjBAXyA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=env%2Creact%2Cstage-2&prettier=false&targets=&version=7.17.12&externalPlugins=&assumptions=%7B%7D) uses WeakMaps as well – Christian Vincenzo Traina May 17 '22 at 14:45
  • By the way, there are alternatives: you can set the property as `{writable: false}`, you can omit the setter, etc... – Christian Vincenzo Traina May 17 '22 at 14:46
  • Thanks for shedding some light on this! – Christopher Flodin May 18 '22 at 06:40

1 Answers1

0

Classes aren't just syntactical sugar anymore because of 3 reasons:

  • They have private fields
  • All classes have a special property [[isClassConstructor]]
  • You can use instanceof with classes but not with function constructors
xijdk
  • 450
  • 4
  • 8
  • 1
    I agree with 1 & 2 but not 3. You can use `instanceof` on any function. [Basic example](https://www.typescriptlang.org/play?jsx=0#code/GYVwdgxgLglg9mABABQKYCcDOCAUBKRAbwFgAoRRKACxkwDowBDAW1UQF5EAiAIzh64BuMgF8yZCAmwAbVHWlwA5jjCoA7igzYkMMJiiNIqOME1YEeIA) – kelsny May 17 '22 at 14:39