What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code:

class BoardTypeResponse {
  created_on: string;
  name: string;
  threads: string[];
  updated_on: string;
  _id: string;
  delete_password: string;
  loading: BoardLoadingType;
  error: BoardErrorType;

  constructor(params: {
    name?: string;
    delete_password?: string;
    _id?: string;
  }) {
    this.created_on = this.now();
    this.name = params.name || 'TEST BOARD NAME';
    this.threads = [];
    this.updated_on = this.now();
    this._id = params._id || this.genUuidV1();
    this.delete_password = params.delete_password || this.genUuidV1();
    this.loading = {
      update_name: false
    };
    this.error = {
      update_name: ''
    };
  }
  private genUuidV1 = () => uuidv1();
  private now = () => new Date().toISOString();
}

The issue with this created object is that it exposes methods genUuidV1 and now in the returned object, which were intended to be private:

{
  created_on: '2019-09-16T16:26:49.885Z',
  name: 'UPDATED CREATE BOARD TEST',
  threads: [],
  updated_on: '2019-09-16T16:26:49.885Z',
  _id: 'c8ebf4d0-d89e-11e9-81ae-1dc34f066a52',
  delete_password: 'abcd123',
  loading: [Object],
  error: [Object],
  genUuidV1: [Function],
  now: [Function]
}

I do not want genUuidV1 and now to be visible when returned. How can I hide them?

Answer №1

Create a custom method for returning data

class BoardTypeResponse {
    created_on: string;
    name: string;
    threads: string[];
    updated_on: string;
    _id: string;
    delete_password: string;
    loading: BoardLoadingType;
    error: BoardErrorType;

    constructor(params: {
        name ? : string;
        delete_password ? : string;
        _id ? : string;
    }) {
        (this.created_on = this.now()),
        (this.name = params.name || 'TEST BOARD NAME'),
        (this.threads = []),
        (this.updated_on = this.now()),
        (this._id = params._id || this.genUuidV1()),
        (this.delete_password = params.delete_password || this.genUuidV1()),
        (this.loading = {
            update_name: false
        });
        this.error = {
            update_name: ''
        };
    }
    genUuidV1 = () => uuidv1();
    now = () => new Date().toISOString();
    getObject = () => {
        return {
            created_on: this.created_on,
            name: this.name,
            threads: this.threads,
            updated_on: this.updated_on,
            _id: this._id,
            delete_password: this.delete_password,
            loading: this.loading,
            error: this.error,
        };
    };
}

Example of usage:

Invoke the getObject() method

let obj = new BoardTypeResponse();
let y = obj.getObject();

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

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

What is the procedure for passing arguments to Google signIn in a NextJS backend?

I am currently working on implementing a role-based Google sign-in feature in a Next.js 13 app using next-auth. This setup involves calling two different tables to create users based on their assigned roles. For the database, I am utilizing mongodb/mongoo ...

Crafting jQuery Plugins with Object-Oriented Programming

Curious about the latest techniques for creating jQuery Plugins? There are so many different methods out there, it's hard to know which one is most effective. Could you recommend any helpful resources or templates for developing jQuery Plugins using ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

How come eslint is unable to detect all files within a directory, yet it can detect a single file?

Here is the organization of my files and directories. https://i.stack.imgur.com/YWNw3.png I am looking to set up some eslint rules for my code detection. In my .eslintrc file, I have included these configuration settings. { "extends": "airbnb", "ru ...

Show text using AJAX when the form is submitted

I'm in the process of creating a basic form with a submit button (see below). My objective is to allow users to enter text into the input box, click submit, and have the page refresh while displaying the entered text in a div element. The user's ...

Arranging sequence of jQuery functions

I have implemented a loop using jQuery that iterates through specific elements on an HTML page. During each iteration, I switch over a variable and add HTML code to particular locations. The issue arises when one of the appends requires importing another ...

I would like to include the value of the "file_id" variable in the href attribute of an appended HTML element, but it seems

<div id="invite_popup"> </div> $(".invite_button2").click(function(){ var file_id = $(this).data("id"); //alert(file_id); var popup2 ='< ...

Styling Result received from Web API call within an array

I am currently working on a function call that retrieves the result of an SQL query in an array format. app.get('/alluser', (req, res) => { console.log("All Users") user.getAllUsers(function (err, result) { if (!err) ...

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Guide to sending both JSON data and form data in a single request using Laravel 9

I am working on a form where I need to input multiple images that will be converted into JSON format. The HTML for my form: create.blade.php <form method="post" action="{{ route('m_announcement.store') }}" enctype="mu ...

Angular 11 Working with template-driven model within a directive

My currency directive in Angular 8.2 formats currency fields for users by using the following code: <input [(ngModel)]="currentEmployment.monthlyIncome" currency> @Directive({ selector: '[ngModel][currency]', providers: [Curr ...

Ways to condense a text by using dots in the middle portion of it

How can I dynamically shorten the text within a container that varies in width? The goal is to replace the strings between the first and last words with dots so that it fits within the container. For example, Sydney - ... - Quito. It should only replace wh ...

Is it necessary to specify the server-side script within the "routes" directory?

I'm currently developing a NodeJS Express application and from what I gather, the communication between the server and client is achieved by incorporating an AJAX script in a JavaScript file (on the client-side) and implementing a listener function (f ...

Storing data in a text or HTML file using server-side JavaScript

Currently, I am working on a JavaScript form that involves saving user-entered variables to either a .txt file or a new webpage with the variables pre-filled in the inputs. I know that JavaScript cannot directly manipulate the user's machine, but I am ...

Is there a way to determine if npm packages are accessing and misusing my system's environment variables?

Apologies if this seems nonsensical. But including a code snippet like this: // to illustrate I'm utilizing a source from https://www.npmjs.com/package/got got.post(maliciousUrl, {json: process.env}) Is it enough to leak environment variables to an u ...

Triggering an event upon completion of ng-repeat's execution

I am facing a challenge in updating the style of a specific element after ng-repeat has finished changing the DOM. The directive I have implemented for triggering ng-repeat works perfectly fine when adding items to the model, but it does not get called whe ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...