Sharing Top Content from the Angular-sphere.

‘Private Variables in JavaScript’ by Marcus Noble

  • For this technique we set the key of the WeakMap to be the instance of the object the private properties belong to and we use a function (which we’ve called ) to create or return an object that all properties will be stored within.
  • This technique has the benefit of not having the private properties shown on the instance when iterating over the properties or when doing but it relies on a WeakMap being available outside of the class itself which could be accessed and manipulated.
  • All of the techniques shown so far still allow private properties to be accessed from outside the class, closures gives us a way of fixing that.
  • We can also intercept calls to and manipulate the output for our private properties: – – Now putting it all together: – – Proxies are currently my favourite method of creating private properties in JavaScript.
  • Currently the proposal focuses on private class properties and not private functions or private members of object literals, these may come later.

JavaScript has had a lot of improvements lately with new syntax and features being added all the time. But some things don’t change, everything is still an object, pretty much everything can be altered at runtime and there is no concept of public/private properties. But there are some tricks we can use to change some of this ourselves, in this post I am going to look at the various ways in which we can implement private properties.

In 2015 JavaScript had classes introduced that provided a familiar way of working with objects for those coming from more classical C-based languages like Java and C#. It becomes quickly apparent though that these classes aren’t quite like what you are used to – there are no modifiers for properties to control access and all properties need to be defined within functions.

So how can we go about protecting data that shouldn’t change during runtime? Let’s take a look at some options.

The first and most established method was to use a specific naming convention to indicate that a property should be treated as private. This usually had the property name prefixed with an underscore (e.g. ). This didn’t prevent the value from being access or modified but rather relied on an understanding between different developers that this value should be treated as off-limits.

For a slightly more restrictive option you can use…

‘Private Variables in JavaScript’ by Marcus Noble