Adding a method to a subclass of Array is not allowed

I'm trying to create a subclass of the Array object using the following code. It works perfectly when running in the browser. However, if I save this code in a .js file and include it with a <script> tag, the .add() method becomes undefined.

class CustomArray extends Array {
  constructor(data) {
    super(...data);
  }

  add(item) {
    this.push(item);
  }

}

const customArr = new CustomArray(['element1', 'element2']);

console.log(customArr);      // -> ['element1', 'element2']
console.log(customArr.add);  // -> undefined

When loading the page, the .add() method is undefined. Yet, pasting the exact same code into the console makes it work.

What could be causing this?

Update: I also have Babel.js (v6.x) for transpilation, which turned out to be the issue, as explained by Fuechter in his answer.

Answer №1

Solution:

class CustomCollection extends Array {
  constructor(data) {
    super(...data);
    this.add = function(item) {
      this.push(item);
    }
  }
}

Reasoning:

The ability to extend native classes is not supported by Babel. This feature was eliminated in version 5.2.17 due to technical issues (refer to this commit)

The removal was necessary as there were functionality problems, as evidenced by the bug:

It is unlikely that this capability will be reinstated, as it cannot be adequately replicated. We may need to wait for browsers to natively support it (some currently have experimental compatibility). Consequently, behaviors might differ across various web browsers.

Additional Reading: Link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Vue with Nuxt.js: A Guide to Parsing POST Request Parameters from External Sources

I am currently facing an issue with accessing the POST request parameters from an external form in my nuxt app. Despite trying to utilize the "asyncData" method, I continue to receive an "undefined" value when attempting to access the submitted parameter t ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

Accepting insecure certificates in Chrome with Selenium-Webdriver in JavaScript: A Step-by-Step Guide

After generating a test script using Selenium-IDE in Javascript-Mocha format, I encountered an issue with an insecure certificate when trying to access a remote URL locally. To address the problem, I need to modify the generated TestScript to include Chro ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

What methods can I use to ensure that images remain at the forefront without relying on Z-Index?

My website design includes a feature where an image pops up next to an underlined word when hovered over. The issue is that the images are supposed to always be on top, but the underlined words are appearing over them. I suspect there is a conflict in the ...

Troubleshooting issue with asp.net jquery datepicker functionality

Having recently delved into the world of JavaScript and jQuery, I'm encountering some issues that I can't seem to resolve. My gut feeling is that the problem lies in the reference to the jQuery files not working properly, but I could be mistaken. ...

Tips for maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

How is the rendering of a confirm/alert decided?

While browsing, I stumbled upon this intriguing query related to alerts and confirm dialogs, such as the one generated by alert('Hello World!'). My quest was to find a method to modify the text on the 'ok' and 'cancel' buttons ...

Tips to minimize a responsive Bootstrap 4 menu by clicking elsewhere

When using my bootstrap nav menu on desktop, it closes when clicking outside of it. However, this feature doesn't work on mobile devices. I attempted to modify some code from a codepen to match the classes on my website, but it didn't work. Bel ...

Guide to utilizing an Ajax response object

Here is the code I am using to display data based on values selected from dropdowns: $("#botao-filtrar").click(function(){ $(".mask-loading").fadeToggle(1000); $.ajax({ url: 'datacenter/functions/filtraDashboardGeral.php', as ...

Issue with cancel button click in Jquery confirm window not being resolved

I have been encountering issues with opening a confirmation dialog in JavaScript despite having the code in place. The dialog is supposed to have 'yes' and 'no' options. function ConfirmDialog(obj, title, dialogText) { if (!dialogC ...

What is the best way to manipulate the canvas "camera" in HTML?

I am currently developing a 3D game that involves navigating through skyboxes. My goal is to have the camera respond to user input, specifically detecting key presses (using WASD controls) to move the camera accordingly. Do you have any suggestions on how ...

it appends an additional closing curly brace without incrementing the level by 1

Struggling with an issue where an extra } keeps getting added to the JSON file and the level value won't increment by 1. I attempted to save the original level value to a text file, then add 1 to it after a one-second delay. if(xpout > 100) { ...

Can someone explain why I am consistently receiving the value of undefined when accessing the file Object?

Hi there, I'm new to this so I could really use some assistance... I'm currently working on an API where only registered users can upload a card with an image of their asset for rent. In my cards.js file, I have a post request that should respo ...

Screen the $http request information prior to transmission

Angular has a built-in feature that removes properties with a prefix of $$ from request data or params objects. I want to filter out my own UI-specific properties that I don't want to send to the server, but I don't want to rely on using $$. Is ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

The multiple-choice selection tool is not displaying any choices

I am having an issue with my ng-repeat code in conjunction with the jquery multiple-select plugin. Despite using this plugin for a multiple select functionality, the options generated by ng-repeat are not visible. Below is the code snippet in question: & ...

The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the sam ...

What is the best method to position images in the same way as seen in the screenshot

Any tips on aligning images shown in the screenshot? Please note that the images will be from the backend. https://i.stack.imgur.com/LnYLM.jpg I experimented with code to position images using top, right, left, and bottom properties, but it becomes cumb ...