Javascript / Coffeescript使用哈希函数作为参数
我有一些看起来像这样的Coffeescript(提前表示歉意):
doc = new ChargerServerDoc(Chargers.find({id:site.id}), site) doc.set_defaults().merge().needs_update update: (id, doc) -> Chargers.update id, $set: doc, (error, result) -> if error run_stats.error_count += 1 "error" else run_stats.update_count += 1 "update" return insert: (doc) -> Chargers.insert doc, (error, result) -> if error run_stats.error_count += 1 "error" else run_stats.insert_count += 1 "insert" return
它应该创build一些文档,并实现插入或更新到数据库作为callback。
needs_update: (callbacks = null) -> console.log inspect arguments if callbacks is null return true unless @is_equal(@working_document, @retrieved_document) return false else console.log """ callbacks not null: insert: #{inspect callbacks['insert']} update: #{inspect callbacks['update']} """ data = @get() if @is_equal(@working_document, @retrieved_document) throw 'requires update callback' if _.isEmpty(callbacks.update) return callbacks.update.call(this, data._id, _.omit(data, '_id')) else throw 'require insert callback' if _.isEmpty(callbacks.insert) return callbacks.insert.call(this, _.omit(data, '_id'))
正如你所看到的, needs_update
函数被console.log
语句所包含。 这是在node.js中运行的,它是一个在运行时启动的事情。 所以在节点检查器中观察并不容易。 至less我还没有想出如何。
无论如何,这个有趣的部分是console.log inspect arguments
。 inspect
只是将对象转换为JSONstring,所以我可以阅读它。 结果总是{"0":{}}
。
而这就是我卡住的地方。 我可以看到它传递了一个散列,但散列中没有任何内容。 更奇怪的是,当我用纯JavaScript写手的时候也会出现这种情况。
我试图减less这个并重现它无济于事。 此代码工作:
h = f1: (a) -> 'one' f2: (b) -> 'two' test = (fn) -> console.log fn.f1.call() console.log fn.f2.call() test(h)
有没有人看到为什么第一个代码失败,减less的例子工程?
谢谢!
你没有正确使用_.isEmpty
。 从精美的手册 :
isEmpty
_.isEmpty(object)
如果可枚举对象不包含任何值(不可枚举自己的属性),则返回true 。 对于string和类似数组的对象
_.isEmpty
检查length属性是否为0。
函数不是一个可枚举的对象,也不是一个string或类似数组的对象。 你给_.isEmpty
东西,它不明白,所以你正在调用未指定的行为。 原来, _.isEmpty
返回true
的东西,它不明白。
如果你想看看是否有什么function, _.isFunction
可能会更好地为你服务:
throw 'requires update callback' unless _.isFunction(callbacks.update)