DEV Community

Nick Mulder
Nick Mulder

Posted on

4 3

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →