Published
Edited
Oct 17, 2021
5 stars
Insert cell
Insert cell
constructor = (spec) => {
const {member} = spec // deconstruct member from spec object (rather than individual parameters)
const {other} = otherConstructor(spec) // use the result of some other constructor
const method = () => {
// because of closure you have full access to spec, member, other, method, even when constructor is done
// plus, you don’t use the ‘this’ object
}
// return all the methods that need to be public in a single object
return Object.freeze({
// freezing is really important as it allows you to have a high integrity object
// that cannot be confused or corrupted
// the only way to get access to the member data is through the methods
// that gives us highly reliable objects
method,
other,
})
}
Insert cell
otherConstructor = (spec) => ({
// put whatever key-value pairs you see fit, including an ‘other’
})
Insert cell
Insert cell
/**
* @param {Object} spec a specification object
* @return {Object}
*/
createFoo = (spec) => {
// private state
let { value } = spec; // selectively read from spec

// public, immutable interface
return Object.freeze({
add: (number) => value += number,
value,
reset: (number = 0) => value = number,
});
};
Insert cell
foo = createFoo({ value: 42 });
Insert cell
foo.add(1);
Insert cell
foo.add(7)
Insert cell
foo.reset(100)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more