如何在coffeescript中传递参数给匿名函数
How to pass arguments to anonymous function in coffeescript?
基本上我需要在coffeescript中传递一个参数给一个匿名函数,我已经没有主意了。
这是我的代码:
audio = {
sounds: {},
sources: [{
wind: 'sounds/wind.mp3'
}],
load: (callback) ->
this.totalFiles = Object.size(this.sources[0])
for key of this.sources[0]
sound = new Howl({ src: [this.sources[0][key]] })
self = this
sound.once('load', (key) =>
(key) ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
(key)) <- THIS ARGUMENT PASSING DOES NOT COMPILE CORRECTLY
loop: (name) ->
this.sounds[name].loop(true)
console.log this.sounds
}
使用callback.call():
的代码load: (callback) ->
this.totalFiles = Object.size(this.sources[0])
for key of this.sources[0]
sound = new Howl({ src: [this.sources[0][key]] })
self = this
sound.once('load', (key) =>
callback.call(() ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
, key)
)
使用callback.call()或callback.apply()我得到相同的结果,相同的编译javascript。我试着在我需要的地方添加(键)在已经编译的javascript中,它按预期工作。
对象大小:
Object.size = (obj) ->
size = 0
for key in obj then if obj.hasOwnProperty(key) then size++
return size
在stackoverflow上找到的一个很好的辅助函数
你的代码有一些问题可能是隐藏了真正的问题:
- 不一致的缩进
-
self = this
对sound.once
的回调是一个胖箭头函数,表示行self.sounds[key] = this
this和self是相同的 - 包含大量不必要的大括号。
- 对象属性定义中逗号使用不一致。
我想,真正的问题是你在试图呼叫生命,而你需要父母:
sound.once('load', ((key) =>
(key) ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
)(key))
除了你过度使用了key
这个名字。你有一个函数,你部分地应用了一个名为key的参数,然后返回的函数也接受一个名为key的参数?是哪一个?
这个对我很有用:
sound.once('load', ((key) =>
() ->
self.sounds[key] = this
if Object.size(self.sounds) == self.totalFiles
if typeof callback == 'function' then callback()
)(key)
)
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 函数未将值作为参数传递
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 为什么不'我们在javascript中使用函数参数的数据类型
- 你好,这是测试用例,我必须在函数中传递n个参数
- JavaScript - 多参数函数,它是多个图像库的字符串
- 如何从两个参数函数返回随机整数
- 以无点风格在Ramda中编写一个无参数函数
- JS:将单参数函数转换为可链接函数
- 正则表达式类似于Javascript中的参数函数
- 将 $' 值传递给替换的关联参数函数
- "这个“;在参数函数中
- 如何向jquery插件发送参数函数
- 将参数函数Node.js从一个js传递到另一个js
- 如何在javascript参数函数中传递PHP post方法字符串
- 装饰 Javascript Promise.then 以便参数函数接收附加参数
- 正在分析setInterval ID'是的's参数函数
- 如何根据一个参数函数计算年龄
- 对象参数/函数和/或三元运算符混淆