Utilize an Immediately-Invoked Function Expression (IIFE) class in TypeScript

In an attempt to create a model class with privacy, I have implemented a class with closures in the Answer model file:

export class Answer {
  getId;
  getText;

  constructor(id: string, text: string) {
    const idPrivate = id;
    const textPrivate = text;

    this.getId = () => idPrivate;
    this.getText = () => textPrivate;
  }
}

This class can be utilized in other files in the following manner:

import {Answer} from '../shared/model/Answer';
...
const answers: Array<Answer> = [];
answers.push(new Answer('1', '1'));

Now, with the introduction of ES6 Symbol, I am attempting to achieve the same functionality, but I am facing challenges in exporting and using the function. Here is the new code implementation:

const Answer = (() => {
  const idPrivate = Symbol();
  const textPrivate = Symbol();

  class Answer {
    constructor(id: string, text: string) {
      this[idPrivate] = id;
      this[textPrivate] = text;
    }

    getId() {
      return this[idPrivate];
    }

    getText() {
      return this[textPrivate];
    }
  }

  return Answer;
})();

export {Answer};

How can I use this Immediately Invoked Function Expression (IIFE) function? For example, when trying to execute the following code:

const answer = Answer('ss', 'ss');

I encounter the error message: "Method expression is not of Function type". How can I correctly invoke the Answer constructor?

Answer №1

When we instantiate classes in JavaScript, we can use the 'new' keyword, for example: new Answer()

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

What purpose does the by.js locator serve in Protractor/WebDriverJS?

Recently, I've come across a new feature in the Protractor documentation - the by.js(): This feature allows you to locate elements by evaluating a JavaScript expression, which can be either a function or a string. While I understand how this locat ...

Ensure that ExpressJS response includes asynchronous try/catch handling for any errors thrown

Currently working with ExpressJS version 4.16.0, NodeJS version 10.15.0, along with KnexJS/Bookshelf, and encountering issues with error handling. While errors are successfully caught within my application, the problem arises when trying to retrieve the e ...

Angular Material 7 now allows you to create a link for an entire row!

Currently, I am utilizing Angular Material 7 tables (mat-table) and my goal is to create a link for an entire row so that it leads to a detailed page display. The specific requirement is to have a functional link that can be opened in a new tab, which mea ...

NX - A comprehensive UI library featuring Storybook integration and individually exported components

As I delve into the world of Nx with Angular (fairly new to both), I am on a quest to create a component library that serves two main purposes: Capable of running Storybook Allowing components to be imported individually, rather than having to drag in the ...

Issues with the typings for the toPromise function in WebStorm have been identified

I'm encountering an issue with WebStorm not recognizing the typings for the toPromise function on 'rxjs', despite having updated it. Is there a way I can troubleshoot this and fix it? Strangely, the code still runs successfully despite the ...

Troubleshooting: JQuery - Applying CSS to dynamically generated elements

I used JQuery to dynamically generate a table, but I'm having trouble applying CSS to the columns. You can see an example at this Codepen link here. Specifically, I need to set the width of the first column to 100px. Could someone please assist me wi ...

Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then dis ...

Transmit information using the buttonRenderer feature in Ag-Grid for Angular applications

Struggling to transfer data between two unrelated components by clicking on a cell in ag-Grid and passing the data to a form component. I utilized the buttonRenderer function to extract row data from ag-Grid, but I'm unsure how to pass it to the secon ...

Error: The service object is unable to bind to ngModel in Angular 5 due to a TypeError, as it cannot read the property 'state' of undefined within Object.eval

Within my service, I have an object declared: public caseDetails = { partyId: '', address: { state: '', city: '', zip: '', street: '' } } I am trying to bind these objects to i ...

Tips for updating components with fresh data in Next.JS without having to refresh the page

As part of my Todo-App development project, I am utilizing technologies such as Next.JS, Prisma, Typescript, and PostgreSQL. The data retrieval process involves the API folder interacting with the database through Prisma. CRUD operations on the Task table ...

Dynamic Form Submission - Displaying Notifications for Success and Failure

While I have managed to successfully submit my form using PHP, I am currently facing some challenges with AJAX. Whenever I submit the form, an error message pops up as if 'res' is false instead of true. Despite my efforts to troubleshoot and rese ...

Exploring the possibilities: Utilizing HTML5, File API, and jQuery to

I have a form displayed in a dialog and it includes a "submit" button which, when clicked, utilizes jQuery to send the form data to the server via AJAX. However, I encountered an issue where the uploaded file was always null. After researching on Google, I ...

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Troubleshooting HTTP requests in Angular JS when dealing with nested scopes

This particular question is derived from a previous answer found at this link. In my current scenario, I am attempting to initiate an http request where one of the data values that needs to be sent is represented in the view as {{selectedCountry.shippin ...

Reactjs slider causes unexpected useState behavior

I created an autoplay Slider with three cards using the useEffect hook. However, the manual "previous" and "forward" buttons are not functioning correctly. The useState function is not updating values as expected, leading to unexpected changes in state. ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

Using JQuery, retain only the initial N elements in a list and discard the rest

I'm looking to streamline a list of items in the DOM by keeping only the first N items, ideally through the use of slice and remove methods. Could someone provide me with the JQuery syntax for removing items that come after the first N in the list? ...

Using iMacros to assign a variable the value of another variable

Running an imacro to automate the addition of sub-domain DNS records through the 123reg front end has presented some challenges due to my specific naming convention. I am mapping two sets of domains as follows: - x.x.x.1 to x.x.x.128 on domain1.com - x.x. ...

Use the row().data function with the datatables.net plug-in to fetch data from a specific column in a

UPDATE: Removed my video on YouTube, but here is a straightforward solution: $(document).on('click', '.edit_btn', function() { var rowData = $('#example').DataTable().row($(this).parents('tr')).data(); }); "Funct ...