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)、默认参数、剩余参数、展开操作符等。

相关推荐
维吉斯蔡5 小时前
【VS Code / Cursor】文件夹右键快捷打开与文件类型自动关联
开发语言·程序人生·学习方法
猫猫不是喵喵.6 小时前
Vue3 Props 属性
前端·javascript·vue.js
luj_17687 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT7 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
xcLeigh8 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
zmzb01038 小时前
C++课后习题训练记录Day175
开发语言·c++
脱胎换骨-军哥9 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠9 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
爱吃牛肉的大老虎10 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
bbq粉刷匠10 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法