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?