类的一大应用就是多态。多态是一个面向对象编程的高级术语----“一个东西可编程很多不同的东西,但不是任何东西”。[引自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));

最新文章

  1. 然并卵,腾讯QQ认证空间又再次关闭申请
  2. Openwebrtc
  3. Xamarin.Forms入门学习路线
  4. Linux LSM(Linux Security Modules) Hook Technology
  5. Java Hour 16 来个CURD吧!
  6. [mysql] mysql 5.6.27 innodb 相关参数
  7. Android - 安装 windows 7 安装 Android SDK 的时候出现的问题!(Connection to https://dl-ssl.google.com refused)
  8. (转)HiddenField控件的使用
  9. 逗号" , "表达式
  10. Python 中psutil 模块的安装
  11. graphical Layout调大一点
  12. python中字符串中一些函数的用法
  13. NSDateFormatter相关整理
  14. Cordova IOT Lesson002
  15. golang的包管理---vendor/dep等
  16. switch留个爪,之后还需要再研究下
  17. PHP开发——基础
  18. 实现一个简单的vue-router
  19. hadoop 在centos中的搭建
  20. windows下使用命令行运行PHP

热门文章

  1. CSS的三种引入方式
  2. css中文乱码与替换字符
  3. 普通硬件就能破解GSM A5加密算法
  4. Quartz Core框架之CALayer
  5. The first day to learn Englisht
  6. Android ScrollView与ListView的冲突解决办法汇总
  7. 学习笔记:CSS3的filter属性
  8. wdcp的安装方法与常见问题
  9. Android 学习第17课,使用文件的数据存储(4种存储模式)
  10. mysql group by后 拼接某一字段