为何在JavaScript中可将变量当作函数调用?函数表达式解析
Great question! Let's unpack why this works using your code as an example.
First, let's recap your code for clarity:
const result = (numberOne, numberTwo) => { if(numberOne > numberTwo){ return true; } else { return false; } }; console.log(result(1, 2)); // Calling the variable as a function
Here's the core reason this works:
In JavaScript, functions are first-class citizens. That means functions are treated like any other value—you can assign them to variables, pass them as arguments to other functions, return them from functions, and yes, call them through the variables that hold their reference.
Let's break down what's happening in your code step by step:
- You're creating an arrow function expression:
(numberOne, numberTwo) => { ... }is a function object that compares two numbers and returns a boolean. - You're assigning this function object to the variable
result. Soresultdoesn't hold a regular value like a number or string—it holds a reference to the function you just created. - When you write
result(1, 2), you're not "calling the variable" itself. You're using the variable to access the function object it points to, then invoking that function with the arguments1and2.
A quick comparison to drive the point home
This works exactly the same way as calling a function declared with a standard function statement:
function result(numberOne, numberTwo) { return numberOne > numberTwo; } console.log(result(1, 2)); // Same calling syntax!
The only difference is how the function gets linked to the result identifier. With a function statement, the identifier is created automatically. With a function expression, you explicitly assign the function to a variable. But in both cases, result references a function object, so using () to invoke it works identically.
One small note
Your arrow function is technically "anonymous" (it doesn't have its own internal name), but since you've assigned it to result, you have a named reference to it that lets you call it whenever you need.
内容的提问来源于stack exchange,提问作者BitFlippa

