CoffeeScript 對(duì)象的鏈?zhǔn)秸{(diào)用

2022-06-29 15:27 更新

對(duì)象的鏈?zhǔn)秸{(diào)用

問(wèn)題

你想調(diào)用一個(gè)對(duì)象上的多個(gè)方法,但不想每次都引用該對(duì)象。

解決方案

在每次鏈?zhǔn)秸{(diào)用后返回this(即@)對(duì)象

class CoffeeCup
    constructor:  ->
        @properties=
            strength: 'medium'
            cream: false
            sugar: false
    strength: (newStrength) ->
        @properties.strength = newStrength
        this
    cream: (newCream) ->
        @properties.cream = newCream
        this
    sugar: (newSugar) ->
        @properties.sugar = newSugar
        this

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庫(kù)使用類(lèi)似的手段從每一個(gè)相似的方法中返回選擇符對(duì)象,并在后續(xù)方法中通過(guò)調(diào)整選擇的范圍修改該對(duì)象:

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

對(duì)我們自己對(duì)象而言,一點(diǎn)點(diǎn)元編程就可以自動(dòng)設(shè)置這個(gè)過(guò)程并明確聲明返回this的意圖。

addChainedAttributeAccessor = (obj, propertyAttr, attr) ->
    obj[attr] = (newValues...) ->
        if newValues.length == 0
            obj[propertyAttr][attr]
        else
            obj[propertyAttr][attr] = newValues[0]
            obj

class TeaCup
    constructor:  ->
        @properties=
            size: 'medium'
            type: 'black'
            sugar: false
            cream: false
        addChainedAttributeAccessor(this, 'properties', attr) for attr of @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
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)