functions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Functions & Scope Skill

函数与作用域技能

Quick Reference Card

速查卡片

Function Styles

函数风格

javascript
// Declaration (hoisted)
function greet(name) { return `Hello, ${name}!`; }

// Expression (not hoisted)
const greet = function(name) { return `Hello, ${name}!`; };

// Arrow (lexical this)
const greet = (name) => `Hello, ${name}!`;
const greet = name => `Hello, ${name}!`;  // Single param
const getUser = async (id) => await fetch(`/api/${id}`);
javascript
// Declaration (hoisted)
function greet(name) { return `Hello, ${name}!`; }

// Expression (not hoisted)
const greet = function(name) { return `Hello, ${name}!`; };

// Arrow (lexical this)
const greet = (name) => `Hello, ${name}!`;
const greet = name => `Hello, ${name}!`;  // Single param
const getUser = async (id) => await fetch(`/api/${id}`);

Scope Rules

作用域规则

Global Scope
  └── Function Scope
        └── Block Scope (let/const)
javascript
const global = 'accessible everywhere';

function outer() {
  const outerVar = 'accessible in outer + inner';

  function inner() {
    const innerVar = 'only accessible here';
    console.log(global, outerVar, innerVar); // All work
  }
}
Global Scope
  └── Function Scope
        └── Block Scope (let/const)
javascript
const global = 'accessible everywhere';

function outer() {
  const outerVar = 'accessible in outer + inner';

  function inner() {
    const innerVar = 'only accessible here';
    console.log(global, outerVar, innerVar); // All work
  }
}

Closure Pattern

闭包模式

javascript
function createCounter() {
  let count = 0;  // Private state

  return {
    increment: () => ++count,
    decrement: () => --count,
    get: () => count
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
javascript
function createCounter() {
  let count = 0;  // Private state

  return {
    increment: () => ++count,
    decrement: () => --count,
    get: () => count
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2

This Binding Rules

this绑定规则

Context
this
Value
Global
window
/
global
Object methodThe object
Arrow functionLexical (outer)
call/apply/bind
Explicit value
Constructor (
new
)
New instance
javascript
// Explicit binding
fn.call(thisArg, arg1, arg2);
fn.apply(thisArg, [args]);
const bound = fn.bind(thisArg);
上下文
this
全局环境
window
/
global
对象方法该对象
箭头函数词法(外部)上下文
call/apply/bind
显式指定的值
构造函数(使用
new
新实例
javascript
// Explicit binding
fn.call(thisArg, arg1, arg2);
fn.apply(thisArg, [args]);
const bound = fn.bind(thisArg);

Advanced Patterns

高级模式

javascript
// IIFE (Immediately Invoked)
const module = (function() {
  const private = 'hidden';
  return { getPrivate: () => private };
})();

// Currying
const multiply = a => b => a * b;
const double = multiply(2);
double(5); // 10

// Memoization
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  };
}
javascript
// IIFE (Immediately Invoked)
const module = (function() {
  const private = 'hidden';
  return { getPrivate: () => private };
})();

// Currying
const multiply = a => b => a * b;
const double = multiply(2);
double(5); // 10

// Memoization
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  };
}

Troubleshooting

问题排查

Common Issues

常见问题

ProblemSymptomFix
Lost
this
undefined
or wrong value
Use arrow fn or
.bind()
Closure loop bugAll callbacks same valueUse
let
not
var
Hoisting confusionUndefined before declarationDeclare at top
TDZ errorReferenceErrorMove
let
/
const
before use
问题症状修复方案
this
丢失
undefined
或错误值
使用箭头函数或
.bind()
闭包循环Bug所有回调使用相同值使用
let
而非
var
变量提升混淆声明前访问得到undefined在作用域顶部声明变量
TDZ错误ReferenceError(引用错误)
let
/
const
移至使用位置之前

The Classic Loop Bug

经典循环Bug

javascript
// BUG: var is function-scoped
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3

// FIX: Use let (block-scoped)
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2
javascript
// BUG: var is function-scoped
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3

// FIX: Use let (block-scoped)
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2

Debug Checklist

调试检查清单

javascript
// 1. Check this context
console.log('this is:', this);

// 2. Verify closure captures
function test() {
  let x = 1;
  return () => { console.log('x:', x); };
}

// 3. Check hoisting
console.log(typeof myFunc); // 'function' or 'undefined'?
javascript
// 1. Check this context
console.log('this is:', this);

// 2. Verify closure captures
function test() {
  let x = 1;
  return () => { console.log('x:', x); };
}

// 3. Check hoisting
console.log(typeof myFunc); // 'function' or 'undefined'?

Production Patterns

生产环境模式

Factory Pattern

工厂模式

javascript
function createLogger(prefix) {
  return {
    log: (msg) => console.log(`[${prefix}] ${msg}`),
    error: (msg) => console.error(`[${prefix}] ${msg}`)
  };
}

const apiLogger = createLogger('API');
apiLogger.log('Request received');
javascript
function createLogger(prefix) {
  return {
    log: (msg) => console.log(`[${prefix}] ${msg}`),
    error: (msg) => console.error(`[${prefix}] ${msg}`)
  };
}

const apiLogger = createLogger('API');
apiLogger.log('Request received');

Debounce/Throttle

防抖/节流

javascript
function debounce(fn, delay) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
}
javascript
function debounce(fn, delay) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
}

Related

相关内容

  • Agent 02: Functions & Scope (detailed learning)
  • Skill: fundamentals: Variables and basics
  • Skill: asynchronous: Async functions
  • Agent 02: 函数与作用域(详细学习)
  • Skill: fundamentals: 变量与基础
  • Skill: asynchronous: 异步函数