我正在尝试使用Ramda学习功能性javascript,而我却坚持这一点。这是JS Bin:http://jsbin.com/kozeka/
这是代码:
const date = new Date()
const addDays = R.add(date.getDate())
const getDate = R.compose(date.setDate, addDays)
console.log(date.setDate(date.getDate() + 6)) //Works
console.log(date.setDate(R.add(date.getDate(), 6))) // Works
console.log(date.setDate(addDays(6))) //Works
console.log(getDate(6)) //Doesn't Work
但是我收到了这个错误。我做错了什么?
"TypeError: Method Date.prototype.setDate called on incompatible receiver undefined
at setDate (<anonymous>)
at http://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js:6:3064
at http://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js:6:182
at kozeka.js:10:38"
答案 0 :(得分:1)
问题是setDate
作为函数传递时会丢失绑定的date
实例。
这可以通过在将方法传递给date
时将方法显式绑定到compose
来解决:
const getDate = R.compose(date.setDate.bind(date), addDays)