在javascript中覆盖匿名const函数[重复]

问题描述 投票:0回答:1

我试图和朋友一起解决这个问题。

假设您有这样的函数:

const foo = function(i) { return function(j){ return 2 * j } };

我如何用不同的方法覆盖foo

假设我想重用foo,使用不同的匿名函数来执行类似function(j){ return 3 * j; };的操作

我该怎么办?

编辑:我看到this post,但这是变量。我正在特别询问匿名方法。

编辑2:这是一个概念证明,所以让我们说foo是一个const我不能把它变成一个let

javascript ecmascript-6 constants
1个回答
0
投票
  • const用于常量,所以它不适用于覆盖。
  • 如果要覆盖变量,请使用letvar

const constantFunction = x => x + 1;
let variableFunction = x => x + 2;

try {
  variableFunction = x => x + 3;
  console.log('Re-assigning to a variable: DONE');
} catch(e) {
  console.log('Error while re-assigning to a variable');
}

try {
  constantFunction = x => x + 3;
  console.log('Re-assigning to a constant: DONE');
} catch(e) {
  console.log('Error while re-assigning to a constant');
}
© www.soinside.com 2019 - 2024. All rights reserved.