How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class:

class Dataframe extends Object {
  _nrow: number;
  _ncol: number;
  _identity: number[];

  constructor(values: Record<string, any[]>) {
    super();
    this._nrow = values[Object.keys(values)[0]].length;
    this._ncol = Object.keys(values).length;
    this._identity = Array(this._nrow).fill(1);
    Object.assign(this, values);
  }

  // Additional methods can be added here...
}

While this approach works, using Object.assign() causes me to lose the typings on values:

const rawData = {x : [1, 2, 3, 4], y: [5, 6, 7, 8]}   
const data = new Dataframe(rawData)
data.x // Property 'x' does not exist on type 'Dataframe'

I would like to know if there is a method for the class instance to inherit the properties from the values object or perhaps an alternate solution to this issue?

Answer №1

It seems there is a logical inconsistency in this scenario because the use of Record<string, any[]> implies that all string keys must have array values. However, you are also attempting to introduce other string properties that do not align with array values.

My suggestion would be to designate values as a property of the class using the public keyword.

class Dataset extends Object {
  _rows: number;
  _cols: number;
  _ids: number[];

  constructor(public values: Record<string, any[]>) {
    super();
    this._rows = values[Object.keys(values)[0]].length;
    this._cols = Object.keys(values).length;
    this._ids = Array(this._rows).fill(1);
  }

  // Additional methods can be added here...
}

const rawData = {a : [9, 8, 7, 6], b: [3, 2, 1, 0]};
const dataset = new Dataset(rawData);
console.log(dataset.values.a);

JavaScript Playground

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

Tips for selecting an image from the gallery with IONIC 3

Looking for guidance on extracting an image from the gallery in IONIC 3? I attempted to grab an image from the gallery but encountered some issues. Visit this link for more information This resource may also be helpful ...

Having trouble parsing the body parameter in Express for a POST request

I am encountering difficulty in accessing the body parameters of a request using Express: const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const app = express(); con ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

What is the best method to trigger a reevaluation of static parameters?

Explanation behind my question Every day, I am sent two timestamps through MQTT at 01:15 - these timestamps represent the beginning and end of a daily event (in this case, when my children are at school). It may not be the most exciting information for a ...

What is the method to permanently install and enforce the latest version using npm?

We are implementing a private npm module for exclusive use within our organization. Given that the module is managed internally, we have confidence in version updates and changes. Is there a way to seamlessly install this module across multiple projects s ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

Tips for changing the click event of a button with .on/off

My approach for attaching and detaching event handlers is through on()/off(). HTML: <div id='load' class="UnfiledContainer"> <button onclick="loaded()">Try it</button> <p id="demo"></p> </div> JS: ...

Introducing the First Angular Factory

It's high time for me to finally inject my first angular Factory . . . Here is the code I have: .factory('Debts', function($q, $scope){ return MA; }) .controller('Admin', function ($scope, Debts) { $scope.Debts = Deb ...

The connections between module dependencies are unable to be resolved

I'm encountering an issue with the npm link command. Here's the scenario: I have two Angular apps - 1) app-core (published locally) 2) app-main The app-core module has the following dependencies (installed via npm): core rxjs z ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

jquery animation does not reset after event occurs

My script is functioning well to animate my elements, but I am facing an issue where when the function is called again after a timer, the elements move to their correct positions but do not initiate a new animation. The goal of the function updateFlights( ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

What is the best way to input an argument into my Javascript code using the command line?

Whenever I run my JavaScript file called "login.js" from the command line using "node login.js", I find it necessary to manually edit the URL inside the file if I want to change it. It would be more convenient for me if I could pass the URL as a command l ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

HTML/JavaScript - Ways to show text entered into an input field as HTML code

One dilemma I'm facing involves a textarea element on my website where users input HTML code. My goal is to showcase this entered HTML code in a different section of the webpage. How should I approach this challenge? The desired outcome is similar to ...