Function Reference and Execution

In JavaScript, functions can reference and execute

Reference functions: When you assign a function name to a variable, the variable will contain a reference to the function. At this point, the function is not executed immediately, but is referenced. For example: 

function sayHello() {
  console.log("Hello!");
}

const hello = sayHello; // 将 sayHello 函数的引用赋值给 hello 变量

hello(); // 执行 hello 变量,实际上是调用 sayHello 函数

Execute function: When you add parentheses after the function name, the function will be executed immediately, and the result of function execution will be returned. For example: 

 

function addNumbers(num1, num2) {
  return num1 + num2;
}

const sum = addNumbers(5, 7); // 执行 addNumbers 函数,并将执行结果赋值给 sum 变量

console.log(sum); // 将 sum 的值(12)打印到控制台

 

In summary, referencing a function and executing a function are different concepts in JavaScript. In general, a function can be used by referencing it instead of executing it immediately when passed as a variable or when code is executed at a specific point in time (such as an event handler). And when you need to get the execution result of the function, you need to execute the function. 

Guess you like

Origin blog.csdn.net/weixin_69811594/article/details/130943464