与变量值同名的函数存在,但是接收到typeError,为什么?

Javascript: Function with same name as variable value exists but receiving typeError, Why?

本文关键字:typeError 为什么 函数 存在 变量值      更新时间:2023-09-26

我不明白为什么我得到"Uncaught TypeError: ops is not a function",而ops持有multiply,因此ops()解析为multiply(),并在范围内定义了multiply()函数。

var product = 1;
var sum = 0;
var x = parseInt(prompt("Enter a No. ", 10)); 
var ops = prompt("Addition/ Multiplication", "multiply");
var y = x;
var operation_type = function (ops){
  var ops = ops;
  return ops;
}
var ops = operation_type(ops);
// console.log(ops);
console.log(ops(x));
// ops(x);
function addition (x) {
   for (i=0; i< x; i++) {
     sum = sum + y;
     y = y - 1;
   } 
   sum = "Recursive sum of " + x +  " is: " + sum; 
  document.getElementById('result').innerHTML = sum;
}
function multiply(x) {
   for (i=0; i< x; i++) {
    product = product*y;
    y = y - 1; 
   }
   product = "Recursive Product of " + x +  " is: " + product; 
  document.getElementById('result').innerHTML = product;
}

谢谢bt

var operation_type = function (ops){
  var ops = ops; // useless declaration/assignment
  return ops;    // return original argument value
}
var ops = operation_type(ops);
console.log(ops(x));

operation_type只是返回您传入的值,一个字符串,并将其赋值给ops变量。做ops(x)尝试调用ops,一个字符串,作为一个函数。您可能想要做的是动态选择在x上操作的函数。

operation_type函数应该返回实际的函数对象。指定名称的函数可以使用括号符号(例如:console.log(window[ops](x))):

var operation_type = function (ops){
  return window[ops];
}
var ops = operation_type(ops);
console.log(ops(x));