博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《CoffeeScript应用开发》学习:第五章 CoffeeScript中的类
阅读量:4479 次
发布时间:2019-06-08

本文共 2159 字,大约阅读时间需要 7 分钟。

在CoffeeScript中定义类

在CoffeeScript中,使用class定义类,使用关键字new实例化对象。

给类绑定方法

class Airplane    takeOff: ->        console.log 'Vrroom!'plane = new Airplane()plane.takeOff()

CoffeeScript如何构建Javascript类

CoffeeScript中的类型系统基于JavaScript的原型继承实现。上面的代码生成的JavaScript代码为:

var Airplane;Airplane = (function() {    function Airplane() {}    Airplane.prototype.takeOff = function() {      return console.log('Vrroom!');    };    return Airplane;})();

上面的例子中,函数先声明空构造函数,并将takeOff函数绑定到类的原型上。

保持对象属性状态

状态存储在绑定到对象的属性里。使用@运算符实现。

class Airplane    describle: ->        "A #{@color} plane"plane = new Airplane()plane.color = 'white'console.log plane.describle # 输出white

在对象中调用其他方法

class Airplane    takeOff: (eta) ->        @taxi()        console.log "#{s}..." for s in [eta..0]        console.log 'Vrrroom'    taxi: ->        if Math.random() > 0.5            console.log 'Taxiing...'

@something实际上是this.something的别名。我们甚至@替换出现的this。可以将@作为this作为参数传递。

在类定义的外面绑定方法

CoffeeScript提供::运算符,以简单实现对象原型的访问。如:

Date::getYearAE = ->    monthOffset = if @getMonth() < 11 then 1 else 0    @getFullYear() - 1944 - monthOffsettoday = new Date()console.log "It is the year #{today.getYearAE()} AE" # 输出 It is the year 71 AE

上面使用::运算符的CoffeeScript代码编译为

Date.prototype.getYearAE = function() {    var monthOffset;    monthOffset = this.getMonth() < 11 ? 1 : 0;    return this.getFullYear() - 1944 - monthOffset;  };

可以看到::使用原型来实现把函数绑定到类。

构造函数

只要加上名字为constructor的方法。同时,如果在构造函数列表中使用@命名标识符,则自动赋值给同名属性

class Train    constructor: (@numCars, @type = 'diesel') ->        @load = 0        @capacity = @numCars * 100

类的静态方法调用

静态方法为绑定到类本身,在没有任何实例化的对象时,可以作为单独的引用使用。在CoffeeScript中,使用@开头的函数为静态函数。例:

同时,也可将静态属性绑定到类。

class Bicyle    @WHEELS = 2    @frameSizeByHeight: (rideHeight) ->        Math.floor rideHeight * 0.82Bicyle.frameSizeByHeight 10   # 调用静态方法console.log Bicyle.WHEELS    # 输出 2

继承

在CoffeeScript中,类定义使用extends表明这个类继承自另一个类。

class Automobile    honk: ->        console.log 'Beep!'class Truck extends Automobile    honk: ->        super()        console.log 'Wee-oo wee-oo wee-oo'

同时,CoffeeScript继承也支持重载方法,只要在子类中重新定义与父类同名(参数不要求匹配)的方法即可。同时,在重载方法内部,可以使用super()函数

转载于:https://www.cnblogs.com/xyb930826/p/6008401.html

你可能感兴趣的文章
vue项目中icon图标的完美引入
查看>>
C语言指针
查看>>
Java的安装
查看>>
0920 JSON数据 蓝懿
查看>>
Azure Cosmos DB 使用费用参考
查看>>
【嵌入式开发】写入开发板Linux系统-模型S3C6410
查看>>
C# 子线程与主线程通讯方法一
查看>>
006——修改tomacat的编码
查看>>
《C程序设计语言》笔记 (八) UNIX系统接口
查看>>
git常用命令
查看>>
Android必知必会-获取视频文件的截图、缩略图
查看>>
(转)理解Bitblt、StretchBlt与SetDIBitsToDevice、StretchDibits
查看>>
ViurtualBox配置虚拟机Linux的网络环境
查看>>
VLC 媒体播放器
查看>>
勿忘国耻2018/09/18
查看>>
Jenkins部署码云SpringBoot项目
查看>>
多标签分类(multi-label classification)综述
查看>>
史上最全面的Spring-Boot-Cache使用与整合
查看>>
图的遍历(深度优先与广度优先搜索两种方案)
查看>>
快速读入模板
查看>>