[英]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)
}
即将函数分配给getContent
和getParents
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.