The mysterious tale of missing objects

We need to pass some parameters to the constructor and use message passing to call methods.const Person = name => { // Constructor parameter const greeting = 'Hello'; // A private field return (message, …args) => { // The message-passing interface switch(message){ // dispatching methods case 'get-name': return name; case 'set-name': return name = args[0] case 'greet': return console.log(`${greeting} ${name}!`); default: console.error( `Reference error. Method "${message}" was not found.` ); } }};const me = Person('Pawel');me('greet');me('set-name', 'Paul');console.log('–>', me('get-name'));me('greet');me('bye');/*The output isHello Pawel!–> PaulHello Paul!Reference error..Method "bye" was not found.*/It works..But the biggest part of the “class” is just a giant switch..It is going to be common for all constructors and has to be extracted..That switch even has its own name..It is a “dispatcher”..It dispatches a message to the function..Actually, it could be implemented as a lookup table, an array, a map or whatever.So let’s extract it and use our object constructor to store a lookup table.const odd = list => list.filter((_, i) => i % 2);const even = list => list.filter((_, i) => !(i % 2));const Obj = (…args) => message => odd(args)[even(args).indexOf(message)]; const dispatch = (…methods) => (message, …args) => { const method = Obj(…methods)(message); return method?.method(…args) : console.error( `Reference error. Method "${message}" was not found.` ); }const Person = name => { const _greeting = 'Hello'; let _name = name; return dispatch( 'get-name', () => _name, 'set-name', name => _name = name, 'greet', () => console.log(`${_greeting} ${_name}!`), );};The “dispatch” function gets as a parameter a lookup table and maps a message to the corresponding method..By the way, as we see later, the table could have more than one level of mapping.For now, we created a constructor of objects which accepts parameters..We could define private and public fields and methods.Do you want to implement “protected”?.Many different levels of protection?. More details

Leave a Reply