首页 > 解决方案 > Can't understand this simple JavaScript code behavior

问题描述

The following function make_f(n) attempting to return a function such that when the user call it, it prints the numbers n, n-1, .., 0.

The logic is to try build the return function (f) with every iteration but it just print "1" infinity. Why is that and how should I fix it? Thanks.

(You can think of 'write(i)' as 'console.log(i)' if you want.)

function make_f(n) {
  var i;
  var f;
  f = function () { write("0");};
  for (i = 1; i <= n ; i++) {
    f = function () { write(i.toString()); f();};
  }
  return f;
}
make_f(10)();

标签: javascript

解决方案


Your assumption that f() would still reference its previous function "version" is invalid because both f and i are defined in the function scope (using var), hence by returning from the outer-most function (as well as inside the loop), f already points to itself and you're ending-up nowhere.

If you'll use let instead, your code will work as expected (although it's not a recommended way to achieve whatever is it you're trying to achieve):

function make_f(n) {
  var f = function() { console.log(0); };

  for (let i = 1; i <= n ; i++) {
    let prev = f;
    f = function () { console.log(i); prev();};
  }

  return f;
}

make_f(10)();

推荐阅读