如何在coffeescript中传递参数给匿名函数

How to pass arguments to anonymous function in coffeescript?

本文关键字:参数 函数 coffeescript      更新时间:2023-09-26

基本上我需要在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 = thissound.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)
    )