如何将参数传递给 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 中我需要它的地方添加 (key),它按预期工作。

对象大小:

Object.size = (obj) ->
        size = 0
        for key in obj then if obj.hasOwnProperty(key) then size++
        return size

在Whosebug上找到的一个很好的辅助函数

您的代码有一些问题可能隐藏真正的问题:

  • 缩进不一致
  • self = this sound.once 的回调是一个粗箭头函数,这意味着该行 self.sounds[key] = this这个和自己一样
  • 包括很多不必要的牙套。
  • 对象 属性 定义中逗号的使用不一致。

据我所知,实际问题是您正在尝试调用 IIFE,并且需要括号:

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 的参数,然后返回的函数 also 接受一个名为 key 的参数?是哪个?

这对我有用:

sound.once('load', ((key) =>
    () ->
        self.sounds[key] = this
            if Object.size(self.sounds) == self.totalFiles
                if typeof callback == 'function' then callback()
        )(key)
    )