I don't know what the correct term is to name this type of functions, so here is a little of what I have and want to achieve.
const registrar = {
usuario: (params) => {},
empresa: (params) => {},
}
export default registrar;
All good so far, I can call my father register and access his methods
registrar.usuario('Test')
But I would like to extend my functionality a bit more, perhaps to be able to add more methods to the user method, that is:
registrar.usuario('Test').disabled(true)
Being able to continue creating sub methods to that other method. How can I achieve this?
You want to make yourself a utilitarian object to create others. Or a factory.
Formally, your object
registrar
has no methods. It has keys whose value is a function. but could you putAnd they would be methods.
You don't say if the invocation of the method to register a user sends a request, persists in a DB, modifies the DOM, etc etc. but whatever it does, and all the more so if you later want to add logic to the created entity, that's not the right place .
The factory can function as a registry that knows what models are in the system, but does not have to know the differences in the domain logic of each one when creating them. For example (apply to the regulation of your country),
The correct thing (or a little more correct) would be to encapsulate the logic of users and companies in classes. With the user, for example:
In your factory:
With that, the following would leave a user instance in your variable
newUser
And incidentally it would be perfectly valid to disable it "on the fly" with
The bad thing is that it doesn't return a user, but you could do a little modification so that the methods that modify attributes of the instance return the instance itself
And with that you could put:
And your variable would still have a user instance.
Just as you wanted to add the method that disables it now, you're going to want to add another method later. For example, to notify the user by mail. For that to make sense, it would also have to be instantiated with an email
And you could do, for example:
Did you notice that I declared your user factory using a spread parameter?
instead of
That had a reason to be, because after all the modifications we made to the User class, the factory hasn't changed at all . I didn't need to change it for the new method or the extra parameter.
Due to a simple design decision, we save ourselves from modifying the factory in the future every time you change the logic of the created entities.
To achieve something like what you show in your example, you would have to use something like this: