Before asking questions, I just started studying JavaScript, so I am not familiar with it.
While I am studying GraphQL, I saw a article about that Object literal is approriate to singleton pattern.
But It is diffucult to understand how Object literal control the scope and obtain private members.
To make some repository by using array in javascript, I wrote code down as below:
import {Person} from "../domain/domain.js";
export default (() => {
let people = [];
let newID = 1;
return {
getNewID() {
newID += 1;
return newID - 1;
},
addPerson(name, age) {
let person = new Person(this.getNewID(), name, age);
people.push(person);
return person;
}
...
}
})();
It works good, but It was hard to understand private members and this scope.
I think that the returned values should be an object literal, just as
{
getNewID() { newID += 1; ... },
addPerson(name, age) { let person = new Person(this.getNewID(), ... },
}
(1) In getNewID(), How can it find the newID varaible? It seems there is no variable to refer values in that function. It is difficult to understand how it works.
(2) In addPerson(name, age), If I change the function as arrow function, how it does change the scope of this and how should I change the getNewID() in addPerson() to be possible to be referred?