CoffeeScript攻略2.5:鏈式呼叫物件
問題
你想呼叫一個物件上的多個方法,但不想每次都引用該物件。
方案
在每次鏈式呼叫後返回this(即@)物件
class CoffeeCup
properties:
strength: 'medium'
cream: false
sugar: false
strength: (newStrength) ->
@properties.strength = newStrength
@
cream: (newCream) ->
@properties.cream = newCream
@
sugar: (newSugar) ->
@properties.sugar = newSugar
@
morningCup = new CoffeeCup()
morningCup.properties # => { strength: 'medium', cream: false, sugar: false }
eveningCup = new CoffeeCup().strength('dark').cream(true).sugar(true)
eveningCup.properties # => { strength: 'dark', cream: true, sugar: true }
討論
jQuery庫使用類似的手段從每一個相關的方法中返回選擇符物件,並在後續方法中通過調整選擇的範圍修改該物件:
$('p').filter('.topic').first()
對我們自己物件而言,一點點超程式設計就可以自動設定這個過程並明確宣告返回this的意圖。
addChainedAttributeAccessor = (obj, propertyAttr, attr) ->
obj[attr] = (newValues...) ->
if newValues.length == 0
obj[propertyAttr][attr]
else
obj[propertyAttr][attr] = newValues[0]
obj
class TeaCup
properties:
size: 'medium'
type: 'black'
sugar: false
cream: false
addChainedAttributeAccessor(TeaCup.prototype, 'properties', attr) for attr of TeaCup.prototype.properties
earlgrey = new TeaCup().size('small').type('Earl Grey').sugar('false')
earlgrey.properties # => { size: 'small', type: 'Earl Grey', sugar: false }
earlgrey.sugar true
earlgrey.sugar() # => true
相關文章
- CoffeeScript攻略2.1:克隆物件(深複製)物件
- CoffeeScript攻略2.3:CoffeeScrip的type函式函式
- CoffeeScript攻略1.1:嵌入JavaScriptJavaScript
- CoffeeScript攻略1.3:for迴圈
- CoffeeScript攻略3.7:拆分字串字串
- CoffeeScript攻略3.9:匹配字串字串
- CoffeeScript攻略4.2:類似Python的zip函式Python函式
- CoffeeScript攻略2.2:建立一個不存在的物件字面值物件
- CoffeeScript攻略3.8:字串插值字串
- CoffeeScript攻略3.1:重複字串字串
- jQuery鏈式呼叫thisjQuery
- php鏈式呼叫PHP
- js 鏈式呼叫JS
- CoffeeScript攻略4.9:篩選陣列陣列
- CoffeeScript攻略4.8:歸納陣列陣列
- CoffeeScript攻略3.4:查詢子字串字串
- CoffeeScript攻略1.2:比較範圍
- CoffeeScript攻略4.7:對映陣列陣列
- CoffeeScript攻略2.4:建立類變數變數
- CoffeeScript攻略4.10:反轉陣列陣列
- CoffeeScript攻略3.10:生成唯一ID
- CoffeeScript攻略4.1:從陣列生成字串陣列字串
- CoffeeScript攻略4.6:打亂陣列元素陣列
- jQuery的鏈式呼叫jQuery
- Objective C 鏈式呼叫Object
- CoffeeScript攻略4.3:取得陣列最大值陣列
- CoffeeScript攻略4.4:使用陣列交換變數陣列變數
- CoffeeScript攻略4.5:定義陣列範圍陣列
- JavaScript中的鏈式呼叫JavaScript
- Promise 原始碼:then 鏈式呼叫Promise原始碼
- Swift可選鏈式呼叫Swift
- PHP 建立鏈式物件PHP物件
- CoffeeScript攻略3.6:大寫單詞首字母
- jQuery鏈式呼叫例項分析jQuery
- Android總結之鏈式呼叫(方法鏈)Android
- CoffeeScript攻略3.2:把字串轉換為小寫形式字串
- CoffeeScript攻略3.3:把字串轉換為大寫形式字串
- CoffeeScript攻略3.5:清理字串前後的空白符字串