我有一些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
,但我也希望this
在foo.processRow()
内引用类实例-这是它目前没有做的。
在.each
函数外部使用像_this = this
这样的东西并传递它也不是一个很好的解决方案,因为我在processRow
中引用了许多类变量。
有什么想法吗?我是不是漏掉了什么明显的东西?谢谢!
发布于 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
函数的静态属性创建的
https://stackoverflow.com/questions/7261480
复制相似问题