簡體   English   中英

如何在Ramda中訪問構造函數'this'?

[英]How can I access constructor 'this' inside Ramda?

每當我嘗試訪問任何this里面Ramda組合功能( R.compose )我得到undefined ,也許是因為this是“綁定”到Ramda組合功能。

如何使this訪問在Class構造函數中啟動?

this.state在下面的代碼中的getContent內未定義:

export default class FaqStore {
  constructor() {
    this.state = new FaqState()

    this.getParents()
  }

  getContent = R.concat(this.state.parents, R.prop('content'))
  getParents = FaqService.getParents().then(this.getContent)

Felix Kling的答案非常好。 不過,我想從Ramda中添加一些更多的上下文。

Ramda(免責聲明:我是其中一位作者)是關於函數式編程的。 它嘗試做兩件事:使Javascript開發人員更容易轉向更標准的FP實踐,並使FP語言的用戶更容易使用Javascript。 完全沒有強調與面向對象的編碼風格的互操作。

有一次,Ramda確實嘗試確保其某些功能確實維護了this上下文,這將允許它們被用作OOP方法。 但我們完全放棄了這個焦點; 它一直是投機的,沒有任何要求,當我們不小心打破它的某些功能時,我們根本就沒有任何抱怨。 似乎沒有什么理由。 同時,它使我們的實施變得復雜並且傷害了性能。 因此,當我們發現需要重寫函數時,我們不再嘗試確保維護它。

這是有道理的。 有些人認為Ramda是Underscore或lodash的替代品,但這似乎總是向我們傾斜。 這些庫引入了一些FP概念,但它們被設計為在多范式環境中工作,同樣滿足於命令式,OOP或FP代碼庫。 Ramda與眾不同,旨在僅在功能系統中運行良好。 它完全圍繞構建系統的概念構建,通過組合純函數。

由於這些原因,除了Felix所說的一切之外,沒有理由期望Ramda函數能夠保持this情況。

您似乎正在使用公共類字段提案。 執行構造函數本身之前評估以這種方式創建的屬性(步驟8和11)。

即你的代碼相當於

export default class FaqStore {
  constructor() {
    this.getContent = R.concat(this.state.parents, R.prop('content'))
    this.getParents = FaqService.getParents().then(this.getContent)

    this.state = new FaqState()

    this.getParents()
  }
}

這清楚地表明您在初始化之前嘗試訪問this.state

可能解決方案

初始化this.state 之后 ,不要使用提議並直接在構造函數中設置屬性:

export default class FaqStore {
  constructor() {
    this.state = new FaqState()

    this.getContent = R.concat(this.state.parents, R.prop('content'))
    this.getParents = FaqService.getParents().then(this.getContent)

    this.getParents()
  }
}

但是 ,仍然存在一個問題:分配給getParents的值是一個promise。 你不能調用一個promise( this.getParents() )。 也許你真正想要的是為getParents分配一個函數:

this.getParents = () => FaqService.getParents().then(this.getContent)

也許R.concat不返回函數或者,在這種情況下this.getContent也不能被調用。 在那種情況下,你真正想要的是

export default class FaqStore {
  constructor() {
    this.state = new FaqState()

    this.getParents()
  }

  getContent = () => R.concat(this.state.parents, R.prop('content'))
  getParents = () => FaqService.getParents().then(this.getContent)
}

即將函數分配給getContentgetParents

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM