This is an encapsulation pattern.
- Objects There are no classes in Javascript, only objects.
car contains an object with the structure visible in the return . - Functions The external function is anonymous (without a name) and is directly called after the definition (brackets at the end).
- Local area . The
drive function exists only in the environment. You cannot call drive from the outside. - Encapsulation . Using the return statement, you can control which functionality will be available externally and how it will be tagged. Therefore,
car is an object with one attribute named start , which is the definition of the drive function.
If you call car.start without parentheses, you yourself get the definition of the function:
function (model, color) { ... }
This is because functions can be assigned to variables (first-class) without actually calling them so that you can later call predefined functions with the scope of your choice.
If you call car.start(audi, black) , you execute the function with the given parameters and get what is returned by the drive function.
source share