一个函数可以读取另一个函数的绑定吗?

Can a function read the binding of another function?

我目前正在学习 javascript,希望能得到一些帮助。

我一直在尝试创建一个不使用 * 运算符即可将两个数字相乘的程序。我已经找到了比我的方法更简单的方法,但我想知道为什么我编写的代码不起作用:

function addToItself(a) {
  a = a + a;
  return a;
}

function times(b) {
  for (count = 0; count < b; count++) {
    addToItself(a)
  }
  return a;
}

function multiply (x, y) {
  a = x;
  times(y);
}

let output = multiply(5, 2);
alert(output);

它不起作用是因为 addToItself 函数中的绑定“a”具有局部作用域并且 multiply 函数无法读取它还是其他原因?

提前致谢!

问题在于每个变量的范围。在 JavaScript 中,函数内声明的变量的作用域是该函数。这意味着在函数内声明的变量只能在函数内访问。范围是嵌套的,因此全局声明的变量也可以在函数内部访问,尽管通常不鼓励这样做。

此外,函数参数(例如 addToItself 中的 atimes 中的 b)被视为函数范围内的变量。

我建议您查看 MDN docs for "scope" 并熟悉变量在 JavaScript 中的作用域。


我已将您的代码的固定版本包含在下面,以供参考:

function addToItself(a) {
  // I used a new variable here since reassigning to an argument is discouraged
  const twoA = a + a;
  return twoA;
}
console.log('5 + 5 = ' + addToItself(5));

function times(value, times) {
  let temp = 0;
  
  for (let count = 0; count < times; count++) {
    temp += value;
  }
  
  return temp;
};
console.log('5 * 5 = ' + times(5, 5));

不,你不能在另一个函数中读取变量,有更简单的方法,比如

function multiply(x, y) {
  var result = 0;
  for (var count = 0; count < y; count++) {
    result += x
  }
  return result;
}

console.log("5 * 2 = " + multiply(5, 2));