es6的一些方法

  1. 箭头函数 (Arrow Functions)

    javascript`// ES5 函数
    var sum = function(a, b) {
    return a + b;
    };

    // ES6 箭头函数
    const sum = (a, b) => a + b;

    console.log(sum(1, 2)); // 输出 3`

  2. 模板字符串 (Template Literals)

    javascript``// ES5 字符串拼接
    var name = "Alice";
    var greeting = "Hello, " + name + "!";

    // ES6 模板字符串
    let name = "Alice";
    let greeting = Hello, ${name}!;

    console.log(greeting); // 输出 "Hello, Alice!"``

  3. 解构赋值 (Destructuring Assignment)

    javascript`// ES5 对象解构
    var person = {
    firstName: "John",
    lastName: "Doe"
    };
    var firstName = person.firstName;
    var lastName = person.lastName;

    // ES6 对象解构
    const person = {
    firstName: "John",
    lastName: "Doe"
    };
    const { firstName, lastName } = person;

    console.log(firstName); // 输出 "John"
    console.log(lastName); // 输出 "Doe"

    // ES5 数组解构
    var arr = [1, 2, 3];
    var first = arr[0];
    var second = arr[1];

    // ES6 数组解构
    const arr = [1, 2, 3];
    const [first, second] = arr;

    console.log(first); // 输出 1
    console.log(second); // 输出 2`

  4. Promise

    javascript`// 创建一个 Promise
    const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Success!"), 1000);
    });

    // 使用 .then() 处理成功的结果
    promise.then(result => {
    console.log(result); // 输出 "Success!"
    });

    // 使用 .catch() 处理失败的结果
    promise.catch(error => {
    console.log(error);
    });`

  5. 类 (Classes)

    javascript``// ES5 模拟类
    function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    }

    Car.prototype.start = function() {
    console.log(${this.make} ${this.model} (${this.year}) is starting.);
    };

    const car = new Car("Toyota", "Camry", 2020);
    car.start(); // 输出 "Toyota Camry (2020) is starting."

    // ES6 类
    class Car {
    constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    }

    start() {
    console.log(${this.make} ${this.model} (${this.year}) is starting.);
    }
    }

    const car = new Car("Toyota", "Camry", 2020);
    car.start(); // 输出 "Toyota Camry (2020) is starting."``

这些只是ES6中引入的一些特性的简单示例。ES6还有更多其他的特性和改进,例如模块化(Modules)、默认参数、剩余参数、展开操作符等。

相关推荐
代码煮茶3 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
任沫4 小时前
Agent之Function Call
javascript·人工智能·go
默_笙5 小时前
🛬 我让 AI 帮我写了一个打飞机游戏,结果 Canvas 把我整不会了
前端·javascript
梯度不陡5 小时前
AI 到底能不能从零写软件?ProgramBench 和 RepoZero 给出了两种答案
前端·javascript·面试
胡萝卜术7 小时前
滑动窗口最大值:从暴力到单调队列,层层优化全解析
前端·javascript·面试
kyriewen8 小时前
2026 年了,这 6 个 npm 包可以卸载了——浏览器原生 API 已经能替代
前端·javascript·npm
铁皮饭盒9 小时前
bun直接tsx,优雅!
javascript·后端
_柳青杨11 小时前
一文吃透 Node.js 事件循环:从原理到 Node 20+ 重大变更
javascript·后端
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
冬奇Lab1 天前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent