Prototypal inheritance applied to CS example

by abernier

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/spinejs/0.0.4/spine.min.js"></script>
<pre><code>class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move()</code></pre>

JavaScript

var Animal, Horse, Snake, sam, tom;

/*
 * Pseudo-classical
 *
var __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) {
    //for (var key in parent) {
    //  if (__hasProp.call(parent, key)) child[key] = parent[key];
    //}

    function ctor() {
      this.constructor = child;
    }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
    };
Animal = (function() {
  function Animal(name) {
    this.name = name;
  }
  Animal.prototype.move = function(meters) {
    return alert(this.name + (" moved " + meters + "m."));
  };
  return Animal;
})();
Snake = (function() {
  __extends(Snake, Animal);

  function Snake() {
    Snake.__super__.constructor.apply(this, arguments);
  }
  Snake.prototype.move = function() {
    alert("Slithering...");
    return Snake.__super__.move.call(this, 5);
  };
  return Snake;
})();
Horse = (function() {
  __extends(Horse, Animal);

  function Horse() {
    Horse.__super__.constructor.apply(this, arguments);
  }
  Horse.prototype.move = function() {
    alert("Galloping...");
    return Horse.__super__.move.call(this, 45);
  };
  return Horse;
})();
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");*/

/*
 * Prototypal
 *
Animal = {
    name: '',
    move: function (meters) {
        return alert(this.name + (" moved " + meters + "m."));
    }
};

Snake = Object.create(Animal, {
    move: {value: function () {
        alert("Slithering...");
        Animal.move.bind(this, 5)();
    }}
});

Horse = Object.create(Animal, {
    move: {value: function () {
        alert("Galloping...");
        Animal.move.bind(this, 45)();
    }}
});

sam = Object.create(Snake, {
    name: {value: 'Sammy the Python'}
});
tom = Object.create(Horse, {
    name: {value: 'Tommy the Palomino'}
});*/

/*
 * Spine
 */
Animal = Spine.Class.create({
    init: function (name) {
        this.name = name;
    },
    name: null,
 ...