Skip to content

Instantly share code, notes, and snippets.

@StephanHoyer
Last active October 13, 2015 16:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephanHoyer/3f0ecd395c24cc2e142f to your computer and use it in GitHub Desktop.
Save StephanHoyer/3f0ecd395c24cc2e142f to your computer and use it in GitHub Desktop.
Object orientation without new and the in JavaScript

Just saw Douglas Crockfords talk at Craft Conference

http://www.ustream.tv/recorded/46640057

Just tried it and must say, it has a certain beauty in it.

No tangeling with prototypes and this/that fuckup.

var Animal = function(name, legs) {
  legs = legs || 4;

  function toString() {
    return JSON.stringify({
      name: name,
      legs: legs
    });
  },

  // Public API
  return Object.freeze({
    toString: toString,
    get name() { return name },
    get legs() { return legs },
    set legs(newLegs) { legs = newLegs }
  });
}

var Dog = function(name, owner) {
  animal = Animal(name, 4);
  
  function toString() {
    return JSON.stringify({
      name: name,
      owner: owner,
      legs: animal.legs
    });
  }
  
  function bark(sound) {
    return animal.name + ' ' + (sound || 'bark') + 's!';
  }

  // Public API
  return Object.freeze({
    bark: bark,
    toString: toString,
    get name() { return animal.name },
    get legs() { return animal.legs },
  });
}

var foo = Animal('Bruno');

console.log(foo.name);
console.log(foo.toString());
// objects functions can't be changed
foo.toString = function() {
  return 'P4WN3D';
};
console.log(foo.toString());

var dolly = Dog('Dolly', 'Harry');

console.log(dolly.bark());
console.log(dolly.bark('waff'));
console.log(dolly.legs);
console.log(dolly.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment