[英]In CoffeeScript when trying to call a method (@_methodName) in a class it returns undefined
I'm trying to use underscore's debounce function in my code, and I'm passing a method of my class as the first parameter, but _.debounce
is telling me that I'm passing an undefined
parameter where the function should be. 我正在尝试在我的代码中使用下划线的debounce函数,并且我将我的类的方法作为第一个参数传递,但
_.debounce
告诉我,我正在传递函数应该是的undefined
参数。
class SomeClass
click: _.debounce @_save, 600
_save: =>
# Save logic
On the other hand, If I do it like this, it works, but this solution seems kind of ugly. 另一方面,如果我这样做,它可行,但这个解决方案似乎有点难看。
class SomeClass
click: _.debounce ( ->
@_save()
), 600
_save: =>
# Save logic
When I check the generated JS source of both functions, it seems like both should work fine, don't know if I'm missing something from CoffeeScript here. 当我检查生成的两个函数的JS源代码时,似乎两者都应该正常工作,不知道我是否遗漏了CoffeeScript中的内容。
CoffeeScript compiles: CoffeeScript编译:
click: _.debounce @_save, 600
into: 成:
SomeClass.prototype.click = _.debounce(SomeClass._save, 600);
Notice how _save
method is a static property of SomeClass
, ie it is not on the prototype because in your declaration @
refers to the class itself, not its instance. 注意
_save
方法是SomeClass
的静态属性,即它不在原型上,因为在你的声明中@
引用了类本身,而不是它的实例。
Alternatively you can declare your click function in the constructor: 或者,您可以在构造函数中声明您的单击函数:
constructor: ->
@click = _.debounce @_save, 600
This will ensure you have a debounced function per instance, and not a shared one. 这将确保每个实例都有一个去抖动功能,而不是共享功能。
I think, you should try something like this instead: 我想,你应该尝试这样的事情:
class SomeClass
constructor: ->
@click = _.debounce @_save, 600
_save: =>
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.