coffeeScript中类的继承[学习篇]

只是在看深入浅出coffeescript中感觉真的很好,不光是coffe写法简单,生成的js也值得学习,废话不多说了,直接抄个书上的例子

class Pet
    constructor: -> 
        @isHungry = true
    eat: ->
        @isHungry = false

class Dog extends Pet
    eat: ->
        console.log '*crunch,crunch*'
        super()
    fetch: ->
        console.log 'Yip yip'
        @isHungry = true

生成的js

// Generated by CoffeeScript 1.10.0
var Dog, Pet,
  extend = 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; 
  },
  hasProp = {}.hasOwnProperty;

Pet = (function() {
  function Pet() {
    this.isHungry = true;
  }

  Pet.prototype.eat = function() {
    return this.isHungry = false;
  };

  return Pet;

})();

Dog = (function(superClass) {
  extend(Dog, superClass);

  function Dog() {
    return Dog.__super__.constructor.apply(this, arguments);
  }

  Dog.prototype.eat = function() {
    console.log('*crunch,crunch*');
    return Dog.__super__.eat.call(this);
  };

  Dog.prototype.fetch = function() {
    console.log('Yip yip');
    return this.isHungry = true;
  };

  return Dog;

})(Pet);
原文地址:https://www.cnblogs.com/tongchuanxing/p/5716489.html