Javascript jQuery .each() 中的 Coffeescript 'this'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7261480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:32:11  来源:igfitidea点击:

Coffeescript 'this' inside jQuery .each()

javascriptcoffeescript

提问by Arnaud Le Blanc

I have some coffeescript like the following:

我有一些像下面这样的咖啡脚本:

class foo:
    @bar = 'bob loblaw'

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

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

So my problem is: I need thisto reference the .eachcontext inside the loop to get at id, but I also would like thisto reference the class instance inside foo.processRow()---which it does not currently do.

所以我的问题是:我需要this引用.each循环内的上下文来获取 at id,但我也想this引用里面的类实例foo.processRow()--- 它目前没有这样做。

Using something like _this = thisoutside the .eachfunction and passing it around isn't a great solution, either, since I reference many class variables inside processRow.

_this = this.each函数外部使用类似的东西并传递它也不是一个很好的解决方案,因为我在processRow.

Any thoughts? Am I missing something obvious? Thanks!

有什么想法吗?我错过了一些明显的东西吗?谢谢!

回答by Arnaud Le Blanc

jQuery.eachpasses the current element as second parameter of the callback, so you don't haveto reserve thisfor jQuery:

jQuery.each通过当前元素作为回调的第二个参数,所以你不要保留this的jQuery:

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

Notice the use of the fat arrow(=>) syntaxfor the callback function; it binds the function's context to the current value of this. (thisin the callback function is always the same thisas the one at the time you defined the function.)

注意回调函数使用粗箭头( =>) 语法;它将函数的上下文绑定到 的当前值this。(this在回调函数中始终与this您定义函数时的相同。)

回答by Trevor Burnham

You say

你说

Using something like _this = thisoutside the .eachfunction and passing it around isn't a great solution, either, since I reference many class variables inside processRow.

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

This is the most efficient solution, though. JavaScript's thisis a strange beast; you can keep it fixed inside of a nested function using the =>operator, as arnaud576875 sugests in his answer (which is elegant but inefficient), or you can copy thisto another variable (which is efficient but inelegant). The choice is yours.

不过,这是最有效的解决方案。JavaScriptthis是一个奇怪的野兽;您可以使用=>运算符将其固定在嵌套函数内,正如 arnaud576875 在他的回答中所暗示的那样(优雅但效率低下),或者您可以复制this到另一个变量(有效但不优雅)。这是你的选择。

Note that some modern browsers support a bindmethod on every function, which is more efficient than CoffeeScript's =>. There's an open ticket to have =>use the native bindwhen available: https://github.com/jashkenas/coffee-script/pull/1408

请注意,一些现代浏览器bind在每个函数上都支持一个方法,这比 CoffeeScript 的=>. 有一个开放票可以在可用时=>使用本机bindhttps: //github.com/jashkenas/coffee-script/pull/1408

Addendum:Of course, a more efficient alternative than any of the above would be to write

附录:当然,比上述任何一种更有效的替代方法是编写

for element, index in $('#my-table>tr')
  ...

which would also solve your thisproblem.

这也可以解决您的this问题。

回答by Rick

Your code...

你的代码...

class foo
    @bar = 'bob loblaw'

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

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

Is transpiled to...

被转译为...

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;
})();

Which has assumed much about about the current context that it is translating to. Unfortunately, since jQuery manages context, you'll have to be explicit or declare a reference to your class's this.

这对它正在翻译的当前上下文做了很多假设。不幸的是,由于 jQuery 管理上下文,因此您必须明确或声明对类的this.

Incidentally, there are other issues with that generated code, take a look at this reduced case:

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

class foo
    @bar = 'bob loblaw'

    getBar: () ->
        @bar

Transpiles to:

转译为:

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

The results of attempting to use this piece of code:

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

> foo.bar;
"bob loblaw"

> var f = new foo();
undefined

> f.getBar();
undefined

Your code seems to expect that @baris an own property, but it's being created as a static property of the foofunction

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