课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

类变量和实例变量

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

你想创建类变量和实例变量(属性)。

解决方案

类变量

  1. class Zoo
  2. @MAX_ANIMALS: 50
  3. MAX_ZOOKEEPERS: 3
  4. helpfulInfo: =>
  5. "Zoos may contain a maximum of #{@constructor.MAX_ANIMALS} animals and #{@MAX_ZOOKEEPERS} zoo keepers."
  6. Zoo.MAX_ANIMALS
  7. # => 50
  8. Zoo.MAX_ZOOKEEPERS
  9. # => undefined (it is a prototype member)
  10. Zoo::MAX_ZOOKEEPERS
  11. # => 3
  12. zoo = new Zoo
  13. zoo.MAX_ZOOKEEPERS
  14. # => 3
  15. zoo.helpfulInfo()
  16. # => "Zoos may contain a maximum of 50 animals and 3 zoo keepers."
  17. zoo.MAX_ZOOKEEPERS = "smelly"
  18. zoo.MAX_ANIMALS = "seventeen"
  19. zoo.helpfulInfo()
  20. # => "Zoos may contain a maximum of 50 animals and smelly zoo keepers."

实例变量

你必须在一个类的方法中才能定义实例变量(例如属性),在 constructor 结构中初始化你的默认值。

  1. class Zoo
  2. constructor: ->
  3. @animals = [] # Here the instance variable is defined
  4. addAnimal: (name) ->
  5. @animals.push name
  6. zoo = new Zoo()
  7. zoo.addAnimal 'elephant'
  8. otherZoo = new Zoo()
  9. otherZoo.addAnimal 'lion'
  10. zoo.animals
  11. # => ['elephant']
  12. otherZoo.animals
  13. # => ['lion']

警告!

不要试图在 constructor 外部添加变量(即使在 elsewhere 中提到了,由于潜在的 JavaScript 的原型概念,这不会像预期那样运行正确)。

  1. class BadZoo
  2. animals: [] # Translates to BadZoo.prototype.animals = []; and is thus shared between instances
  3. addAnimal: (name) ->
  4. @animals.push name # Works due to the prototype concept of Javascript
  5. zoo = new BadZoo()
  6. zoo.addAnimal 'elephant'
  7. otherZoo = new BadZoo()
  8. otherZoo.addAnimal 'lion'
  9. zoo.animals
  10. # => ['elephant','lion'] # Oops...
  11. otherZoo.animals
  12. # => ['elephant','lion'] # Oops...
  13. BadZoo::animals
  14. # => ['elephant','lion'] # The value is stored in the prototype

讨论

Coffeescript 会将类变量的值保存在类中而不是它定义的原型中。这在定义类中的变量时是十分有用的,因为这不会被实体属性变量重写。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号