CoffeeScript 類變量和實(shí)例變量

2022-06-29 16:46 更新

類變量和實(shí)例變量

問題

你想創(chuàng)建類變量和實(shí)例變量(屬性)。

解決方案

類變量

class Zoo
  @MAX_ANIMALS: 50
  MAX_ZOOKEEPERS: 3

  helpfulInfo: =>
    "Zoos may contain a maximum of #{@constructor.MAX_ANIMALS} animals and #{@MAX_ZOOKEEPERS} zoo keepers."

Zoo.MAX_ANIMALS
# => 50

Zoo.MAX_ZOOKEEPERS
# => undefined (it is a prototype member)

Zoo::MAX_ZOOKEEPERS
# => 3

zoo = new Zoo
zoo.MAX_ZOOKEEPERS
# => 3
zoo.helpfulInfo()
# => "Zoos may contain a maximum of 50 animals and 3 zoo keepers."

zoo.MAX_ZOOKEEPERS = "smelly"
zoo.MAX_ANIMALS = "seventeen"
zoo.helpfulInfo()
# => "Zoos may contain a maximum of 50 animals and smelly zoo keepers."

實(shí)例變量

你必須在一個(gè)類的方法中才能定義實(shí)例變量(例如屬性),在constructor結(jié)構(gòu)中初始化你的默認(rèn)值。

class Zoo
  constructor: ->
    @animals = [] # Here the instance variable is defined

  addAnimal: (name) ->
    @animals.push name

zoo = new Zoo()
zoo.addAnimal 'elephant'

otherZoo = new Zoo()
otherZoo.addAnimal 'lion'

zoo.animals
# => ['elephant']

otherZoo.animals
# => ['lion']

警告!

不要試圖在constructor外部添加變量(即使在elsewhere中提到了,由于潛在的JavaScript的原型概念,這不會(huì)像預(yù)期那樣運(yùn)行正確)。

class BadZoo
  animals: []           # Translates to BadZoo.prototype.animals = []; and is thus shared between instances

  addAnimal: (name) ->
    @animals.push name  # Works due to the prototype concept of Javascript

zoo = new BadZoo()
zoo.addAnimal 'elephant'

otherZoo = new BadZoo()
otherZoo.addAnimal 'lion'

zoo.animals
# => ['elephant','lion'] # Oops...

otherZoo.animals
# => ['elephant','lion'] # Oops...

BadZoo::animals
# => ['elephant','lion'] # The value is stored in the prototype

討論

Coffeescript會(huì)將類變量的值保存在類中而不是它定義的原型中。這在定義類中的變量時(shí)是十分有用的,因?yàn)檫@不會(huì)被實(shí)體屬性變量重寫。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)