Categories: CoffeeScript 教程

CoffeeScript 类方法和实例方法

类方法和实例方法

问题

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

解决方案

类方法

class Songs
  @_titles: 0    # Although its 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 its 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会在对象本身中保存类方法(也叫静态方法),而不是在对象原型中(以及单一的对象实例),在保存了记录的同时也将类级的变量保存在中心位置。

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

4 天 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

1 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

2 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

3 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

4 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

4 周 ago