Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问clear审计通过

modern-javascript-patternsmodern JavaScript 模式

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

271,728

周安装

11,145

GitHub Stars

34,466

下载量

87,912
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:modern-javascript-patterns(modern JavaScript 模式)
来源仓库:https://github.com/wshobson/agents
仓库路径:skills/modern-javascript-patterns
安装命令:
npx skills add https://github.com/wshobson/agents --skill modern-javascript-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/wshobson/agents --skill modern-javascript-patterns

简介

ES6+ 语法和函数式编程模式,用于编写干净、现代的 JavaScript。

  • 掌握箭头函数、解构、扩展运算符、模板文字和增强的对象语法,以实现简洁、可读的代码
  • 使用 Promise.all 和 Promise.race 等组合器实现 async/await 和 Promise 模式来处理异步操作
  • 应用函数式编程技术,包括映射、过滤、归约、高阶函数、组合和纯函数进行数据转换
  • 使用可选链接、无效合并、生成器、迭代器和模块等现代功能来实现健壮、可维护的应用程序
  • 通过去抖动、节流、记忆和惰性求值模式优化性能

SKILL.md

Modern JavaScript Patterns

Comprehensive guide for mastering modern JavaScript (ES6+) features, functional programming patterns, and best practices for writing clean, maintainable, and performant code.

When to Use This Skill

  • Refactoring legacy JavaScript to modern syntax
  • Implementing functional programming patterns
  • Optimizing JavaScript performance
  • Writing maintainable and readable code
  • Working with asynchronous operations
  • Building modern web applications
  • Migrating from callbacks to Promises/async-await
  • Implementing data transformation pipelines

ES6+ Core Features

1. Arrow Functions

Syntax and Use Cases:

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

// Arrow function
const add = (a, b) => a + b;

// Single parameter (parentheses optional)
const double = (x) => x * 2;

// No parameters
const getRandom = () => Math.random();

// Multiple statements (need curly braces)
const processUser = (user) => {
  const normalized = user.name.toLowerCase();
  return { ...user, name: normalized };
};

// Returning objects (wrap in parentheses)
const createUser = (name, age) => ({ name, age });

Lexical 'this' Binding:

class Counter {
  constructor() {
    this.count = 0;
  }

  // Arrow function preserves 'this' context
  increment = () => {
    this.count++;
  };

  // Traditional function loses 'this' in callbacks
  incrementTraditional() {
    setTimeout(function () {
      this.count++; // 'this' is undefined
    }, 1000);
  }

  // Arrow function maintains 'this'
  incrementArrow() {
    setTimeout(() => {
      this.count++; // 'this' refers to Counter instance
    }, 1000);
  }
}

2. Destructuring

Object Destructuring:

const user = {
  id: 1,
  name: "John Doe",
  email: "john@example.com",
  address: {
    city: "New York",
    country: "USA",
  },
};

// Basic destructuring
const { name, email } = user;

// Rename variables
const { name: userName, email: userEmail } = user;

// Default values
const { age = 25 } = user;

// Nested destructuring
const {
  address: { city, country },
} = user;

// Rest operator
const { id, ...userWithoutId } = user;

// Function parameters
function greet({ name, age = 18 }) {
  console.log(`Hello ${name}, you are ${age}`);
}
greet(user);

Array Destructuring:

const numbers = [1, 2, 3, 4, 5];

// Basic destructuring
const [first, second] = numbers;

// Skip elements
const [, , third] = numbers;

// Rest operator
const [head, ...tail] = numbers;

// Swapping variables
let a = 1,
  b = 2;
[a, b] = [b, a];

// Function return values
function getCoordinates() {
  return [10, 20];
}
const [x, y] = getCoordinates();

// Default values
const [one, two, three = 0] = [1, 2];

3. Spread and Rest Operators

Spread Operator:

// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

// Object spreading
const defaults = { theme: "dark", lang: "en" };
const userPrefs = { theme: "light" };
const settings = { ...defaults, ...userPrefs };

// Function arguments
const numbers = [1, 2, 3];
Math.max(...numbers);

// Copying arrays/objects (shallow copy)
const copy = [...arr1];
const objCopy = { ...user };

// Adding items immutably
const newArr = [...arr1, 4, 5];
const newObj = { ...user, age: 30 };

Rest Parameters:

// Collect function arguments
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3, 4, 5);

// With regular parameters
function greet(greeting, ...names) {
  return `${greeting} ${names.join(", ")}`;
}
greet("Hello", "John", "Jane", "Bob");

// Object rest
const { id, ...userData } = user;

// Array rest
const [first, ...rest] = [1, 2, 3, 4, 5];

4. Template Literals

// Basic usage
const name = "John";
const greeting = `Hello, ${name}!`;

// Multi-line strings
const html = `
  <div>
    <h1>${title}</h1>
    <p>${content}</p>
  </div>
`;

// Expression evaluation
const price = 19.99;
const total = `Total: $${(price * 1.2).toFixed(2)}`;

// Tagged template literals
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i] || "";
    return result + str + `<mark>${value}</mark>`;
  }, "");
}

const name = "John";
const age = 30;
const html = highlight`Name: ${name}, Age: ${age}`;
// Output: "Name: <mark>John</mark>, Age: <mark>30</mark>"

5. Enhanced Object Literals

const name = "John";
const age = 30;

// Shorthand property names
const user = { name, age };

// Shorthand method names
const calculator = {
  add(a, b) {
    return a + b;
  },
  subtract(a, b) {
    return a - b;
  },
};

// Computed property names
const field = "email";
const user = {
  name: "John",
  [field]: "john@example.com",
  [`get${field.charAt(0).toUpperCase()}${field.slice(1)}`]() {
    return this[field];
  },
};

// Dynamic property creation
const createUser = (name, ...props) => {
  return props.reduce(
    (user, [key, value]) => ({
      ...user,
      [key]: value,
    }),
    { name },
  );
};

const user = createUser("John", ["age", 30], ["email", "john@example.com"]);

Asynchronous Patterns

1. Promises

Creating and Using Promises:

// Creating a promise
const fetchUser = (id) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) {
        resolve({ id, name: "John" });
      } else {
        reject(new Error("Invalid ID"));
      }
    }, 1000);
  });
};

// Using promises
fetchUser(1)
  .then((user) => console.log(user))
  .catch((error) => console.error(error))
  .finally(() => console.log("Done"));

// Chaining promises
fetchUser(1)
  .then((user) => fetchUserPosts(user.id))
  .then((posts) => processPosts(posts))
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Promise Combinators:

// Promise.all - Wait for all promises
const promises = [fetchUser(1), fetchUser(2), fetchUser(3)];

Promise.all(promises)
  .then((users) => console.log(users))
  .catch((error) => console.error("At least one failed:", error));

// Promise.allSettled - Wait for all, regardless of outcome
Promise.allSettled(promises).then((results) => {
  results.forEach((result) => {
    if (result.status === "fulfilled") {
      console.log("Success:", result.value);
    } else {
      console.log("Error:", result.reason);
    }
  });
});

// Promise.race - First to complete
Promise.race(promises)
  .then((winner) => console.log("First:", winner))
  .catch((error) => console.error(error));

// Promise.any - First to succeed
Promise.any(promises)
  .then((first) => console.log("First success:", first))
  .catch((error) => console.error("All failed:", error));

2. Async/Await

Basic Usage:

// Async function always returns a Promise
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  const user = await response.json();
  return user;
}

// Error handling with try/catch
async function getUserData(id) {
  try {
    const user = await fetchUser(id);
    const posts = await fetchUserPosts(user.id);
    return { user, posts };
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
}

// Sequential vs Parallel execution
async function sequential() {
  const user1 = await fetchUser(1); // Wait
  const user2 = await fetchUser(2); // Then wait
  return [user1, user2];
}

async function parallel() {
  const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);
  return [user1, user2];
}

Advanced Patterns:

// Async IIFE
(async () => {
  const result = await someAsyncOperation();
  console.log(result);
})();

// Async iteration
async function processUsers(userIds) {
  for (const id of userIds) {
    const user = await fetchUser(id);
    await processUser(user);
  }
}

// Top-level await (ES2022)
const config = await fetch("/config.json").then((r) => r.json());

// Retry logic
async function fetchWithRetry(url, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fetch(url);
    } catch (error) {
      if (i === retries - 1) throw error;
      await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
}

// Timeout wrapper
async function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error("Timeout")), ms),
  );
  return Promise.race([promise, timeout]);
}

Functional Programming Patterns

Functional programming in JavaScript centers on pure functions, immutability, and composable transformations.

Key topics covered in references/advanced-patterns.md:

  • Array methodsmap, filter, reduce, find, findIndex, some, every, flatMap, Array.from
  • Higher-order functions — custom forEach/map/filter, currying, partial application, memoization
  • Composition and pipingcompose/pipe utilities with practical data transformation examples
  • Pure functions and immutability — immutable array/object operations, deep cloning with structuredClone

Modern Class Features

ES2022 classes support private fields (#field), static fields, getters/setters, and private methods. See references/advanced-patterns.md for a full example with inheritance.

Modules (ES6)

// Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }

// Default export
export default function multiply(a, b) { return a * b; }

// Import
import multiply, { PI, add } from "./math.js";

// Dynamic import (code splitting)
const { add } = await import("./math.js");

For re-exports, namespace imports, and conditional dynamic loading see references/advanced-patterns.md.

Iterators and Generators

Generators (function*) and async generators (async function*) enable lazy sequences and async pagination. See references/advanced-patterns.md for custom iterator, range generator, fibonacci, and for await...of examples.

Modern Operators

// Optional chaining — safe property access
const city = user?.address?.city;
const result = obj.method?.();

// Nullish coalescing — default only for null/undefined (not 0 or "")
const value = null ?? "default"; // 'default'
const zero = 0 ?? "default";    // 0

// Logical assignment
a ??= "default";   // assign if null/undefined
obj.count ||= 1;   // assign if falsy
obj.count &&= 2;   // assign if truthy

Performance Optimization

See references/advanced-patterns.md for debounce, throttle, and lazy evaluation with generators.

Best Practices

  1. Use const by default: Only use let when reassignment is needed
  2. Prefer arrow functions: Especially for callbacks
  3. Use template literals: Instead of string concatenation
  4. Destructure objects and arrays: For cleaner code
  5. Use async/await: Instead of Promise chains
  6. Avoid mutating data: Use spread operator and array methods
  7. Use optional chaining: Prevent "Cannot read property of undefined"
  8. Use nullish coalescing: For default values
  9. Prefer array methods: Over traditional loops
  10. Use modules: For better code organization
  11. Write pure functions: Easier to test and reason about
  12. Use meaningful variable names: Self-documenting code
  13. Keep functions small: Single responsibility principle
  14. Handle errors properly: Use try/catch with async/await
  15. Use strict mode: 'use strict' for better error catching

For common pitfalls (this binding, promise anti-patterns, memory leaks), see references/advanced-patterns.md.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

30.46%
按下载量换算26,778

Cursor

20.42%
按下载量换算17,952

OpenCode

17.42%
按下载量换算15,314

Gemini CLI

11.13%
按下载量换算9,785

Antigravity

8.18%
按下载量换算7,191

Codex

3.52%
按下载量换算3,095

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills