【发布时间】:2014-04-25 01:15:38
【问题描述】:
我想制作一个 CoffeeScript 函数,即使它被多次调用,它的效果也只运行一次。
其中一种或另一种方式是制作一次可调用函数的好方法吗?额外的do 是一个问题还是实际上更好?
once_maker_a = (f)->
done=false
->
f.call() unless done
done=true
once_maker_b = (f)->
do(done=false)->
->
f.call() unless done
done=true
oa = once_maker_a(-> console.log 'yay A')
ob = once_maker_b(-> console.log 'yay B')
oa()
yay A #runs the function passed to the once_maker
undefined #return value of console.log
oa()
undefined #look, does not reprint 'yay A'
ob()
yay B
undefined
ob()
undefined
我知道http://api.jquery.com/one/ 和http://underscorejs.org/#once,但在这种情况下,不能使用这些库。
【问题讨论】:
-
Underscore implementation 非常接近您的
once_maker_a,除非您不处理f的返回值。 -
这里唯一缺少的是处理传递给原始函数的参数和返回值。除此之外,你有一个相当合理的实现。
-
原来的缩进问题没有了,但是在do(done=false)下缩进失败->
标签: javascript coffeescript functional-programming combinators