簡體   English   中英

為什么循環箭頭不能將胖箭頭綁定到當前環境?

[英]Why does the fat-arrow not bind to the current environment in loop comprehensions?

如果我編譯此CoffeeScript:

    funcs = ((=> console.log i) for i in [0..2])                                                                                                                                                                                          

    funcs[0]()  // Prints 3
    funcs[1]()  // Prints 3
    funcs[2]()  // Prints 3

它產生以下JavaScript:

    (function() {
      var funcs, i;

      funcs = (function() {
        var _i, _results,
          _this = this;
        _results = [];
        for (i = _i = 0; _i <= 3; i = ++_i) {
          _results.push(function() {
            return console.log(i);
          });
        }
        return _results;
      }).call(this);

      funcs[0]();

      funcs[1]();

      funcs[2]();

      funcs[3]();

    }).call(this);

我認為它將具有:

          _results.push((function(i) {
             return function() {
              return console.log(i);
          }})(i));

有人可以解釋為什么不這樣做嗎?

粗箭頭this詞法上綁定this綁定,而不是每個變量都綁定。 使用do通過IIFE捕獲變量。

funcs =
  for i in [0..2]
    do (i) ->
      -> console.log i

閉包不是這樣工作的。 當您從另一個函數范圍返回一個函數時,將得到一個閉包:

var closure = (function(i) {
    return function() {
        console.log(i);
    };
})(i);

這可以通過以下丑陋的CoffeeScript來實現(這里不需要粗箭頭):

funcs = ((do (j=i) -> -> console.log j) for i in [0..2])

我建議您不要將其寫為一行。

好的,在查看了CoffeeScript文檔之后,我相信我已經回答了我自己的問題。 =>僅將函數綁定到this的當前值。 我錯誤地認為它會將所有變量都綁定到它們的當前值。

...雖然具有這樣的功能會很整潔。 也許->>嗎?

當您將咖啡轉換為javascript時,會得到綁定示波器的函數。 問題是:

funcs = (function() {
    var _i, _results,
      _this = this;
    _results = [];
    for (i = _i = 0; _i <= 3; i = ++_i) {
      _results.push(function() {
        return console.log(i);
      });
    }
    return _results;
  }).call(this);

在其中,變量i是綁定的,但是到您調用該函數時,該值為3,並且在每次調用該函數時仍為3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM