NodeJS:函数与匿名函数

NodeJS: function vs. anonymous function

本文关键字:函数 NodeJS      更新时间:2023-09-26

正在进行流冒险NodeJS教程,但我在双工器redux练习中很吃力。

这是我试图使用的,但它不起作用:

var duplexer = require('duplexer2');
var through = require('through2').obj;
module.exports = function (counter) {
  var counts = {};
  var input = through(write, end);
  return duplexer(input, counter);
  var write = function (row, _, next) {
    counts[row.country] = (counts[row.country] || 0) + 1;
    next();
  }
  var end = function (done) {
    counter.setCounts(counts);
    done();
  }
};

这是建议的解决方案,有效:

var duplexer = require('duplexer2');
var through = require('through2').obj;
module.exports = function (counter) {
  var counts = {};
  var input = through(write, end);
  return duplexer(input, counter);
  function write (row, _, next) {
    counts[row.country] = (counts[row.country] || 0) + 1;
    next();
  }
  function end (done) {
    counter.setCounts(counts);
    done();
  }
};

有人能帮我理解使用保存到变量中的匿名函数与仅命名函数之间的区别吗?

不同之处在于吊装。当您使用函数声明语句(即所提出的解决方案中使用的内容)时,它的定义会被"提升"到包含它的范围(读作:函数)的顶部,因此,即使您试图在定义它的代码之前引用它,它也是可用的。

您正在使用变量赋值来定义您的函数。这意味着write在执行var write =语句之前不会有值。在此之前,当write仍然具有值undefined时,您正在尝试使用它。

这意味着你可以通过移动你定义函数的位置来让你的代码工作:

module.exports = function (counter) {
  var counts = {};
  var write = function (row, _, next) {
    counts[row.country] = (counts[row.country] || 0) + 1;
    next();
  };
  var end = function (done) {
    counter.setCounts(counts);
    done();
  };
  var input = through(write, end);
  return duplexer(input, counter);
};

n.b.请勿将函数声明语句命名函数表达式混淆命名函数表达式是非辅助的,就像匿名函数一样:

var boom = getNumber();
var getNumber = function getNumber() { return 3; };