javascript - Coffeescript 访问函数

标签 javascript loops coffeescript

我是 CoffeeScript 的新手,有一个关于访问函数的问题。

鉴于下面的代码,我将如何从构造函数的 for 循环中访问 c​​heckType 函数?

class ApplicationForm.Save
  constructor: (@formItems) ->
    @that = this
    for item in @formItems
      do ->
        checkType(item)

   checkType: (forItem) ->
     console.log(@formItem.find("input").length)

最佳答案

这里似乎有点困惑:

  1. @that = this 没有任何意义。您似乎正在尝试重现常见的 JavaScript 习惯用法:

    var that = this;
    

    这样您就可以在其他地方使用所需的this。但 @ 不用于声明变量(CoffeeScript 自动执行此操作),@ 只是 this. 的简写。你说的是 this.that = this 但这没有任何用处。

  2. 当您需要立即计算循环变量而不是仅仅获取引用时,在循环中使用
  3. do 。常见的情况是这样的:

    for i in [0, 1, 2]
      $(".something#{i}").click -> console.log(i)
    

    无论点击什么内容,该代码都会导致所有内容都显示 2 ,因为所有匿名回调都使用相同的 i 引用。添加 do 只是将循环体包装在自调用函数中,以强制循环变量取消引用,因此:

    for i in [0, 1, 2]
      do (i) ->
        # do something with `i`...
    

    就像这样的 JavaScript:

    for(i = 0; i <= 2; ++i)
      (function(i) {
        // do something with `i`...
      })(i)
    

    您已经将 item 传递给函数,因此 do 是多余的。

  4. 您的 checkType(item) 正在尝试调用不存在的函数。您似乎想要调用 checkType 方法,然后回到 @ 的含义,我们看到您需要使用 @ 来调用this 上的该方法:

    @checkType(item)
    
  5. 您的 checkType 方法有一个 forItem 参数,但您在该方法内使用 @formItem 。但同样,@ 正是我们在 CoffeeScript 中说 this 的方式,因此似乎存在拼写错误的组合(forItemformItem )以及对 @ 含义的一些混淆。您的 checkType 可能应如下所示:

    checkType: (formItem) ->
      console.log(formItem.find("input").length)
    

将所有这些放在一起可以得出:

class ApplicationForm.Save
  constructor: (@formItems) ->
    for item in @formItems
      @checkType(item)
  checkType: (formItem) ->
    console.log(formItem.find("input").length)

关于javascript - Coffeescript 访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33243921/

相关文章:

Javascript 控制页面和用户 View 页面

arrays - 在 leftcalloutaccessoryview 中使用 for loop array 在 swift 注释映射中设置唯一图像

r - 在 for 循环中提取数据并将其 append 到新数据集

javascript - 在 CoffeeScript 中,如何在不意外声明的情况下过滤掉全局数组?

javascript - 类型错误 : Cannot read property 'sortingLevel' of undefined

javascript - 将数据从 firestore 附加到 JavaScript 中的数组

javascript - 如何在 React 中使用外部 jquery 插件

javascript - 使用 javascript 显示 laravel 变量

javascript - 如何获取循环外的循环值

javascript - 绑定(bind) Backbone View 事件时如何使用变量?