ES6+ 特性,箭头函数、解构赋值、模块导入

1. 箭头函数(Arrow Functions)

箭头函数是 ES6 引入的一种简洁的函数定义方式。它的语法更简洁,并且不会绑定自己的 this 值。箭头函数通常用于简化函数表达式。

基本语法

const add = (a, b) => a + b;

特点

  • 简洁:省略了 function 关键字、花括号和 return 关键字(如果函数体只有一行代码)。
  • 没有自己的 this:箭头函数会继承外部函数的 this,而不是创建自己的 this。这在处理回调函数时非常有用。

示例

// 普通函数
function sayHello(name) {
    return `Hello, ${name}`;
}

// 箭头函数
const sayHello = name => `Hello, ${name}`;

// 不需要参数的箭头函数
const getRandomNumber = () => Math.random();

2. 解构赋值(Destructuring Assignment)

解构赋值是一种从数组或对象中提取值的语法,使得赋值操作更加简洁和易读。

数组解构

const numbers = [1, 2, 3, 4];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2

对象解构

const person = {
    name: 'John',
    age: 30,
    city: 'New York'
};
const { name, age } = person;
console.log(name); // John
console.log(age);  // 30

默认值

const [a, b = 2] = [1];
console.log(b); // 2

const { x = 10 } = {};
console.log(x); // 10

嵌套解构

const person = {
    name: 'Jane',
    address: {
        city: 'London',
        postcode: 'SW1A 1AA'
    }
};
const { name, address: { city } } = person;
console.log(name); // Jane
console.log(city); // London

3. 模块导入(Modules)

ES6 引入了模块化语法,使得代码可以被分割成多个模块,每个模块都有自己的作用域,支持导入和导出功能。

导出

命名导出

// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

默认导出

// utils.js
const multiply = (a, b) => a * b;
export default multiply;

导入

导入命名导出

// main.js
import { add, subtract } from './utils.js';
console.log(add(2, 3)); // 5
console.log(subtract(5, 2)); // 3

导入默认导出

// main.js
import multiply from './utils.js';
console.log(multiply(2, 3)); // 6

别名导入

// main.js
import { add as addition, subtract as subtraction } from './utils.js';
console.log(addition(2, 3)); // 5
console.log(subtraction(5, 2)); // 3

动态导入(异步加载模块):

// main.js
async function loadModule() {
    const module = await import('./utils.js');
    console.log(module.add(2, 3)); // 5
}

loadModule();

这些 ES6+ 特性在编写现代 JavaScript 应用程序时非常有用,可以帮助你编写更简洁、易维护的代码。

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值