0

I want to create an object and hide some of its properties.

How do I do this?

For example, to this object:

console.log(new Path2D()); // Path2DĀ {} empty*

In this image, the console is very crowded and confusing.

enter image description here

  • 2
    Does this answer your question? [Is it possible to create a hidden property in javascript](https://stackoverflow.com/questions/2636453/is-it-possible-to-create-a-hidden-property-in-javascript) – kelsny Nov 17 '22 at 16:38
  • 1
    `new Path2D()` has no own properties, so which properties do you want to hide, exactly? Familiarize yourself with [enumerability and ownership of properties](//developer.mozilla.org/en/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) and consider using [private class features](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes/Private_class_fields) or a [closure](/q/111102/4642212). – Sebastian Simon Nov 17 '22 at 16:38

1 Answers1

0

It depends why you want to do that, it's hard to give a precise answer without more details. In most cases there is no need to hide properties (what are you afraid of?), but here are two ways if you really need to:

  • you can use Symbol properties (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), that is new Path2D() would return an object where the keys are not strings but Symbols. This has the advantage that a user of this object can add its own properties to the object without risking clashing with internal properties that your library relies on. It is still possible for someone to access those properties, though, if they really want to.

  • You can hide things in a local variable in a closure. It is much more hidden than with Symbol properties, but it might require thinking about the API differently.

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32