eS6 Deconstructing
by Sam Fereday
JavaScript
// https://davidwalsh.name/spread-operator
console.clear();
// Defines a literal named 'props', assigns a right hand assigned literal to that (initial data)
const { ...props } = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
}
// Creates a component object that'll carry our initialize method
const t = {
// Initialize is designed to run once, and we deconstruct whatever properties we want from the initial data passed,
// and we also define a runtime method that can be used any time throughout the lifecycle of the app
initialize: ({ a, c, e }) => (message) => {
// Initial data is always present since it was already defined
console.log(a, c, e);
// Message changes based on input through app lifecycle
console.log(message);
}
}
// Start things off by initializing the props data in to our component, then binding that to a value for later use
const init = t.initialize(props);
// Since init has been assigned and initialized, we can now also use any runtime methods specified after it and can call them
// any time we need to. Calling t.initialize again won't affect our 'init' const since it's a completely new and isolated call.
init("Runtime message 1...");
init("Runtime message 2...");
init("Runtime message 3...");
// Output should be something like this:
/*
1 3 5
Runtime message 1...
1 3 5
Runtime message 2...
1 3 5
Runtime message 3...
*/
// You shouldn't be able to edit the initial data, or at least shouldn't try to. Our goal here is to keep immutability.
// Best part about all this? Not a 'new' keyword in sight. :)