CoffeeScript 类方法和实例方法


本文整理自网络,侵删。

类方法和实例方法

问题

你想创建类和实例的方法。

解决方案

类方法

class Songs
  @_titles: 0    # Although it's directly accessible, the leading _ defines it by convention as private property.

  @get_count: ->
    @_titles

  constructor: (@artist, @title) ->
    @constructor._titles++     # Refers to <Classname>._titles, in this case Songs.titles

Songs.get_count()
# => 0

song = new Songs("Rick Astley", "Never Gonna Give You Up")
Songs.get_count()
# => 1

song.get_count()
# => TypeError: Object <Songs> has no method 'get_count'

实例方法

class Songs
  _titles: 0    # Although it's directly accessible, the leading _ defines it by convention as private property.

  get_count: ->
    @_titles

  constructor: (@artist, @title) ->
    @_titles++

song = new Songs("Rick Astley", "Never Gonna Give You Up")
song.get_count()
# => 1

Songs.get_count()
# => TypeError: Object function Songs(artist, title) ... has no method 'get_count'

讨论

Coffeescript会在对象本身中保存类方法(也叫静态方法),而不是在对象原型中(以及单一的对象实例),在保存了记录的同时也将类级的变量保存在中心位置。


标签:CoffeeScript

相关阅读 >>

CoffeeScript 类变量和实例变量

CoffeeScript 比较范围

CoffeeScript 关于

CoffeeScript 反转数组

CoffeeScript 命令模式

CoffeeScript 匹配字符串

CoffeeScript 重复字符串

CoffeeScript 数组最大值

CoffeeScript 观察者模式

CoffeeScript 使用 heregexes

更多相关阅读请进入《CoffeeScript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...