What is the best way to utilize the constructor in a JavaScript object so that only the properties within `this` are utilized?

I am looking to instantiate the following class:

class Person {
    firstName;
    lastName;
    birthday;
    constructor(props: Person) {
        {firstName, lastName, birthday} = props
    }
}

var me = new Person({firstName: "donald", 
lastName: "trump",
 middleName: "john"})

My goal is for the constructor to only assign the class properties to "this," resulting in me being

{firstName: "donald", lastName: "trump", birthday: undefined}

One approach I am considering is:

class Person {
    firstName;
    lastName;
    birthday;
    constructor(props: Person) {
        this.{firstName, lastName, birthday} = props
    }
}

var me = new Person({firstName: "donald", lastName: "trump", middleName: "john"})

or a similar solution.

Answer №1

This task can be accomplished in just a couple of lines:

const {fname,lname,DoB} = properties;
Object.assign(this, {fname,lname,DoB});

However, if you're dealing with only three properties, a simpler approach is to:

this.fname = properties.fname;
this.lname = properties.lname;
this.DoB = properties.DoB;

Not only is this method more readable, but it's also slightly quicker. The tradeoff for an extra line is worthwhile.

An alternative option is to modify the constructor signature to destructure the specific properties:

constructor({fname: firstName, lname: lastName, DoB: DateOfBirth}) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.dateOfBirth = DateOfBirth;
}

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 transferring the ngRepeat "template" to an ngDirective with transclude functionality

Example: http://plnkr.co/edit/TiH96FCgOGnXV0suFyJA?p=preview In my ng-directive named myDirective, I have a list of li tags generated using ng-repeat within the directive template. My goal is to define the content of the li tag as part of the myDirective ...

Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages: <div id="contact-us" class="section md-padding bg-grey"> <div id="contact"></div> <script src="/dist/build.js"></script> </div> Included in main.js is: im ...

Set the position of a div element to be fixed

I am currently working on a straightforward application that requires implementing a parallax effect. Here are the methods I have experimented with so far: - Inserting an image within a div with the class parallax. - Subsequently, adding an overlay div ...

Facing difficulty observing Content-Disposition header in create-react-app project

I am using a create-react-app that is being served by express. Express is acting as a proxy for the app and all the application logic resides in CRA. My issue lies in calling an API to download a file. The API sends back a "Content-Disposition" header wit ...

Issue with React/D3.js Density Plot - Error: The <path> attribute d is expecting a number, but received "M10,NaNL12,NaNC14,Na…"

I'm currently working on implementing a Density Plot in React using D3.js, but unfortunately, the plot is not appearing on the screen. Since I don't have much experience with charts and data visualization, I've been trying to follow the exam ...

The message from the Discord bot is not displayed in an embedded format

When using the code below: message.reply('some reply', { embed: { color: 3447003, description: "A very simple Embed!" } }); } the response from my bot will appear as a regular messa ...

When React first fetches data and users move to chat with each other, the state value does not update

Recently, I started learning about React and Node.js as I dive into building a chat application. When a user is clicked for one-on-one chat, I retrieve records from the database using backend Node.js and also incorporate socket.io. In my Chat.js file: imp ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Utilizing the Context API in Next.js to transfer a prop from the layout component to its children

I am encountering difficulties utilizing the context API to globally pass a state in my app's layout. Here is the code for the Layout component: import { useState, useEffect, createContext } from 'react' import useAPIStore from "../store/sto ...

The mui-datatables demo fails to display the code snippet as intended

Just diving into React and attempting to grasp MUI-datatables. The code snippet from the Codebox provided on the library's page isn't displaying in my browser, resulting in an empty page. Surprisingly, the console isn't showing any errors. ...

Choose the initial search result without actually opening it using jQuery

I am working on an HTML file that contains multiple input fields, which get automatically filled when a corresponding item is selected from the auto-complete feature. Here is a snippet of my HTML code: <table class="table table-bordered"> <u ...

Angular is not able to access the value of a promise in a different function after it has been retrieved

I have a form with default values that should be added to the form fields when it appears. There are two functions: #1 for fetching data from the backend and #2 for displaying the form: person$: any; ngOnInit() { this.getPersonData(123) this.buildPer ...

Could you provide me with a demonstration of cross-domain functionality?

Similar Inquiry: Methods to bypass the same-origin policy Let's consider two domains for this example - "" and "". The first domain "" is generating data in JSON format as shown below: { "str_info": [ { "str_name": "Mark ...

Developing a Gulp buildchain: Transforming Typescript with Babelify, Browserify, and Uglify

I've configured a buildchain in Gulp, but when I execute the gulp command, it only utilizes one of the two entry points I specify. My goal is to merge the methods outlined in these two resources: and here: https://gist.github.com/frasaleksander/4f7b ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

JavaScript: Modifying an Array of Matrices

Could anyone assist me with updating a matrix array? I have an initial matrix with preset values and need to update specific coordinates within it. Here is the base matrix: var myMatrix = [ ['-','-','-','-',&ap ...

How to sort WordPress RSS feed in alphabetical order using JavaScript

Currently using WP, but feeling limited due to restricted access to PHP and plugins. Searching for a JAVASCRIPT code solution to fetch RSS feed from a URL and organize the feed titles in ALPHABETICAL order. The JS code can be inserted into the footer and ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...