课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

对象的链式调用

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

问题

你想调用一个对象上的多个方法,但不想每次都引用该对象。

解决方案

在每次链式调用后返回 this(即@)对象

  1. class CoffeeCup
  2. constructor: ->
  3. @properties=
  4. strength: 'medium'
  5. cream: false
  6. sugar: false
  7. strength: (newStrength) ->
  8. @properties.strength = newStrength
  9. this
  10. cream: (newCream) ->
  11. @properties.cream = newCream
  12. this
  13. sugar: (newSugar) ->
  14. @properties.sugar = newSugar
  15. this
  16. morningCup = new CoffeeCup()
  17. morningCup.properties # => { strength: 'medium', cream: false, sugar: false }
  18. eveningCup = new CoffeeCup().strength('dark').cream(true).sugar(true)
  19. eveningCup.properties # => { strength: 'dark', cream: true, sugar: true }

讨论

jQuery 库使用类似的手段从每一个相似的方法中返回选择符对象,并在后续方法中通过调整选择的范围修改该对象:

  1. $('p').filter('.topic').first()

对我们自己对象而言,一点点元编程就可以自动设置这个过程并明确声明返回 this 的意图。

  1. addChainedAttributeAccessor = (obj, propertyAttr, attr) ->
  2. obj[attr] = (newValues...) ->
  3. if newValues.length == 0
  4. obj[propertyAttr][attr]
  5. else
  6. obj[propertyAttr][attr] = newValues[0]
  7. obj
  8. class TeaCup
  9. constructor: ->
  10. @properties=
  11. size: 'medium'
  12. type: 'black'
  13. sugar: false
  14. cream: false
  15. addChainedAttributeAccessor(this, 'properties', attr) for attr of @properties
  16. earlgrey = new TeaCup().size('small').type('Earl Grey').sugar('false')
  17. earlgrey.properties # => { size: 'small', type: 'Earl Grey', sugar: false }
  18. earlgrey.sugar true
  19. earlgrey.sugar() # => true
转载本站内容时,请务必注明来自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号