DEV Community

Nick Mulder
Nick Mulder

Posted on

How to properly extend JS native Classes

In many cases it can be useful to extend native Javascript classes. Though you should be careful as unwanted side-effects might be difficult to pin down. In this example we will be extending the Array class with a simple immutable remove function.

In order the extend a class we want to add a property to the object's prototype

We could simply do the following:

Alt Text

Here we directly extend the classes prototype. We however lack control to define detailed behavior. This causes unwanted side-effects. One of the side-effects is that the property is Enumerable. This causes it to be part of values when using a for...in loop. In order to circumvent this issue and get more control we can instead do the following:

Alt Text

By using Object.defineProperty we are able to control the attributes of our new property.

Top comments (0)