Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Crockford's classless OOP implementation

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.

  • He doesn't specify key-value pairs and instead just comma separates strings.
  • he uses them on the left hand of an assignment

Additionally, what are the advantages provided by freezing the object he returns?

like image 275
Luke Avatar asked Jul 24 '15 16:07

Luke


1 Answers

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;
like image 111
imcg Avatar answered Oct 18 '22 14:10

imcg