zoukankan      html  css  js  c++  java
  • coffeeScript中类的多态[学习篇]

    类的一大应用就是多态。多态是一个面向对象编程的高级术语----“一个东西可编程很多不同的东西,但不是任何东西”。[引自coffeescript深入浅出]

    class Shape
        constructor: (@width) ->
        computeArea: -> throw new Error 'I am an abstract class!'
    
    class Square extends Shape
        computeArea: -> Math.pow @width, 2
    
    class Circle extends Shape
        radius: -> @width / 2
        computeArea: -> Math.PI * Math.pow @radius, 2
    
    showArea = (shape) ->
        unless shape instanceof Shape
            throw new Error 'showArea requires a Shape instance!'
        console.log shape.computeArea()
    
    showArea new Square(2) #4
    showArea new Circle(2) #pi

    生成的javascript

    // Generated by CoffeeScript 1.10.0
    var Circle, Shape, Square, showArea,
      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;
    
    Shape = (function() {
      function Shape(width) {
        this.width = width;
      }
    
      Shape.prototype.computeArea = function() {
        throw new Error('I am an abstract class!');
      };
    
      return Shape;
    
    })();
    
    Square = (function(superClass) {
      extend(Square, superClass);
    
      function Square() {
        return Square.__super__.constructor.apply(this, arguments);
      }
    
      Square.prototype.computeArea = function() {
        return Math.pow(this.width, 2);
      };
    
      return Square;
    
    })(Shape);
    
    Circle = (function(superClass) {
      extend(Circle, superClass);
    
      function Circle() {
        return Circle.__super__.constructor.apply(this, arguments);
      }
    
      Circle.prototype.radius = function() {
        return this.width / 2;
      };
    
      Circle.prototype.computeArea = function() {
        return Math.PI * Math.pow(this.radius, 2);
      };
    
      return Circle;
    
    })(Shape);
    
    showArea = function(shape) {
      if (!(shape instanceof Shape)) {
        throw new Error('showArea requires a Shape instance!');
      }
      return console.log(shape.computeArea());
    };
    
    showArea(new Square(2));
    
    showArea(new Circle(2));
  • 相关阅读:
    JQuery OOP 及 OOP思想的简易理解
    windows下编写shell脚本执行错误
    Kafka常用命令
    OffsetDateTime工具类
    windows下安装consul
    磁盘阵列方案
    shell基本语法记录
    学习CGLIB与JDK动态代理的区别
    Spring源码分析-BeanFactoryPostProcessors 应用之 PropertyPlaceholderConfigurer
    局域网内搭建git
  • 原文地址:https://www.cnblogs.com/tongchuanxing/p/5716508.html
Copyright © 2011-2022 走看看