首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery .each()中的Coffeescript 'this‘

jQuery .each()中的Coffeescript 'this‘
EN

Stack Overflow用户
提问于 2011-09-01 02:15:14
回答 1查看 42K关注 0票数 56

我有一些coffeescript,如下所示:

class foo:
    @bar = 'bob loblaw'

    processRows: ->
        $("#my-table>tr").each ->
            id = $(this).attr("id")
            @processRow id

    processRow: (id) ->
        console.log @bar + id

所以我的问题是:我需要this在循环内引用.each上下文以获取id,但我也希望thisfoo.processRow()内引用类实例-这是它目前没有做的。

.each函数外部使用像_this = this这样的东西并传递它也不是一个很好的解决方案,因为我在processRow中引用了许多类变量。

有什么想法吗?我是不是漏掉了什么明显的东西?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2011-09-01 02:38:45

你的代码...

class foo
    @bar = 'bob loblaw'

    processRows: ->
        $("#my-table>tr").each ->
            id = $(this).attr("id")
            @processRow id

    processRow: (id) ->
        console.log @bar + id

被翻译成..。

var foo;
foo = (function() {
  function foo() {}
  foo.bar = 'bob loblaw';
  foo.prototype.processRows = function() {
    return $("#my-table>tr").each(function() {
      var id;
      id = $(this).attr("id");
      return this.processRow(id);
    });
  };
  foo.prototype.processRow = function(id) {
    return console.log(this.bar + id);
  };
  return foo;
})();

它假设了很多关于它正在翻译到的当前上下文的信息。不幸的是,由于jQuery管理上下文,因此必须显式或声明对类的this的引用。

顺便说一句,生成代码还有其他问题,看一下这个简化的案例:

class foo
    @bar = 'bob loblaw'

    getBar: () ->
        @bar

将文件传输到:

var foo;
foo = (function() {
  function foo() {}
  foo.bar = 'bob loblaw';
  foo.prototype.getBar = function() {
    return this.bar;
  };
  return foo;
})();

尝试使用这段代码的结果如下:

> foo.bar;
"bob loblaw"

> var f = new foo();
undefined

> f.getBar();
undefined

您的代码似乎期望@bar是自己的属性,但它是作为foo函数的静态属性创建的

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7261480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档