Skip to content

函数

一句话解释

函数 是 reusable 块 的 code 那个 执行 任务, 可选地 taking 输入 and returning result.

用大白话说

A function is a named, reusable block of code. You write it once, then call it by name whenever you need it — optionally passing in inputs (parameters) and getting a result (return value) back.

Functions help you avoid repeating yourself (the DRY principle). Instead of writing the same calculation in five places, you write it once as a function and call it five times. If the logic changes, you update only the function.

Functions are the primary way programmers organize and structure code. A typical program is a collection of functions that call each other, each focused on one small job.

示例

javascript
function add(a, b) {
  return a + b;
}

console.log(add(2, 3));  // 5
console.log(add(10, 20)); // 30

添加 是 函数 那个 takes two 参数 ` and b` and 返回 它们的 总和.

工作原理

  1. Define the function with a name and a body (the code to run).
  2. Call the function by name, optionally passing arguments.
  3. The function runs its body, using the arguments as inputs.
  4. If the function has a 返回 statement, it sends a value back to the caller.

常见混淆

  • 容易混淆的对象: 方法

    关键区别: 函数 stands on 它的 own; 方法 是 函数 那个 belongs 到 对象 and 是 called 使用 点 (e.g. 数组.推送()). 所有 方法 是 函数, 但 不 所有 函数 是 方法.

相关术语

相关资源

相关课程

  • 函数

    学习 如何 到 定义 and call 函数

相关项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表