简体   繁体   English

在CoffeeScript中尝试在类中调用方法(@_methodName)时,它返回undefined

[英]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.

相关问题 流星和CoffeeScript:无法调用未定义的方法“帮助器” - Meteor and CoffeeScript: Cannot call method 'helpers' of undefined Coffeescript类中的方法返回函数而不是字符串 - Method in Coffeescript Class returns function instead of string Coffeescript类方法始终返回false - Coffeescript class method always returns false 尝试调用方法时未定义ViewChild组件 - ViewChild component undefined when trying to call method 尝试在类内调用emit方法时,从EventEmitter扩展的类上的未定义“ this” - Undefined 'this' on class extending from EventEmitter when trying to call emit method inside of class 查询返回控制台日志中的项目,但是html显示Uncaught TypeError:尝试在页面上显示时无法调用未定义的方法“ get” - Query returns items in console log, but html is showing Uncaught TypeError: Cannot call method 'get' of undefined when trying to display on the page Coffeescript + Express.js:无法调用未定义的“切片”方法 - Coffeescript + Express.js : cannot call method 'sliced' of undefined CoffeeScript类字段未定义 - CoffeeScript class field is undefined 尝试在JavaScript中使用工厂调用方法时变得不确定 - Getting undefined when trying to call a method using a factory in JavaScript CoffeeScript中的方法调用语法 - Method Call Syntax in CoffeeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM