【问题标题】:In Atom, module not defined using promise and functions在 Atom 中,模块未使用 promise 和函数定义
【发布时间】:2017-01-03 23:58:07
【问题描述】:

我正在使用 Coffeescript 为 Atom 编辑器编写一个包。

我的示例代码:

module.exports =
class DeclarationTree

  createIndexModules: (files, length) =>
    @modules = new Map()
    ...
  
  onClic = (text) =>
    # PROBLEM **@modules** IS UNDEFINED
    file_array = @modules.get(text)
    console.log file_array
    console.log file_array[0], file_array[1]

  getProvider: ->
    providerName: 'hyperclick-provider',
    # getSuggestionForWord gives me a promise
    getSuggestionForWord: (editor, text, range) ->
      range: range, callback: ->
          onClic(text)

当然,@modules 是在调用 onClic() 之前定义的。

我不知道如何解决它,我是 Javascript 的新手。

看起来onClic= () 定义了一个非类的方法,无法访问@module (this.module)

如何在 promise 的回调函数中访问我在类方法中创建的变量?

谢谢!

编辑:使用冒号:感谢 -1 ;)

module.exports =
class DeclarationTree

  createIndexModules: (files, length) =>
    @modules = new Map()
    console.log this.constructor.name # DeclarationTree
    ...
  
  onClic: (text) =>
    # PROBLEM **@modules** IS UNDEFINED
    file_array = @modules.get(text)
    console.log file_array
    console.log file_array[0], file_array[1]

  getProvider: ->
    providerName: 'hyperclick-provider',
    # getSuggestionForWord gives me a promise
    getSuggestionForWord: (editor, text, range) ->
      range: range, callback: ->
          console.log this.constructor.name # Object
          @onClic(text)

获取Uncaught TypeError: this.onClic is not a function 错误。

显然,我无法在 callback 函数中访问与 this 对象相关的任何内容。

【问题讨论】:

    标签: javascript coffeescript atom-editor


    【解决方案1】:

    这可能就像在onClic 之后使用冒号而不是等号一样简单。这就是你的意思吗?

    目前,coffeescript 只是在该类声明范围内编写函数表达式,因此它无法访问 @ / this

    编辑

    您尝试在上下文之外使用this。您需要将函数绑定到要引用的范围。在咖啡脚本中,您可以使用粗箭头函数轻松完成此操作。

    【讨论】:

    • 谢谢,我之前尝试过,但出现错误,我想我无法访问与该对象相关的任何内容。 (我编辑了我的问题)
    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2017-04-14
    • 2014-12-06
    • 2018-07-19
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多