I have been reading about the different ways to do OOP in JS.
Douglas Crockford has an interesting approach in which he doesn't appear to use delegation at all. Instead, to me it appears that he purely utilizes object concatenation as his inheritance mechanism, but its kind of hard for me to tell whats going on and I'm hoping someone can help.
Here is an example that Crockford gives in one of his talks.
function constructor(spec) {
let {member} = spec,
{other} = other_constructor(spec),
method = function () {
// accesses member, other, method, spec
};
return Object.freeze({
method,
other
});
}
And here is an example from a gist
function dog(spec) {
var { name, breed } = spec,
{ say } = talker({ name }),
bark = function () {
if ( breed === 'chiuaua' ) {
say( 'Yiff!' );
} else if ( breed === 'labrador' ) {
say('Rwoooooffff!');
}
};
return Object.freeze({
bark,
breed
});
}
function talker(spec) {
var { name } = spec;
var say = function(sound) {
console.log(name, "said:", sound)
}
return Object.freeze({
say
});
}
var buttercup = dog({ name: 'Buttercup', breed: 'chiuaua' });
I'm confused about a few things.
I have never seen object literals used this way before.
Additionally, what are the advantages provided by freezing the object he returns?
Where he doesn't specify key-value pairs and instead just comma separates strings he's taking advantage of an ES6 feature that converts the variable names of the values into string object keys for you.
{ bark, breed }
is the equivalent of:
{ bark: bark, breed: breed }
The advantage of freezing an Object is immutability. Once an object is frozen it's properties can't be changed.
This is good because it helps avoid some common errors, like trying to change a non-existent property due to misspelling, and stops you (and other coders) redefining or adding methods and properties to the object after it's been created.
EDIT: Another ES6 feature demonstrated here is destructuring.
var { name, breed } = spec;
is the equivalent of:
var name = spec.name,
breed = spec.breed;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With