One of the features I like most in ES6 is destructuring. It introduces a convenient syntax for getting multiple values from arrays or objects in a single step, i.e. do the following:
or like this:
What is even nicer, it works fine in a function definition, too, making it a great replacement for the config object pattern, where instead of providing the large number of parameters, some of them potentially optional, we provide a single plain configuration object and read all the relevant options from the inside the object provided. So, with ES6 destructuring (+default parameters support), instead of this:
we can move all that read-config-and-apply-default-if-needed stuff directly as a parameter:
The code is equivalent and the change doesn’t require any changes at the caller side.
We can use destructuring to provide Angular-like experience for receiving the dependencies by a class or a function that is even more cruft-free as it’s minification-safe and thus doesn’t require tricks like ngAnnotate does.
Here is how it can look from the dependencies consumer side:
Whenever we invoke the
iHaveDependencies function, we need to pass it a single parameter containing the object with
dependency2 keys, but possibly also with others. Nothing prevents us from passing the object with all the possible dependencies there (a container).
So the last thing is to ensure we have one available whenever we create the objects (or invoke the functions):
That’s all. The destructuring mechanism will take care of populating
dependency2 variables within our function seamlessly.
We can easily build a dependency injection “framework” on top of that. The implementation would vary depending on how our application creates and accesses the objects, but the general idea will hold true. Isn’t that neat?
PS. Because the lack of direct ES6 support in the browsers, running that in a browser right now requires transpiling it down to ES5 beforehand. Babel works great for that.