ES6有哪些特性?
-
let
和const
关键字:用于声明变量。let
声明的变量可重新赋值,const
声明的变量是常量,不可重新赋值。 -
箭头函数(Arrow Functions): 箭头函数提供了一种更简洁的函数声明方式,并且改变了 this 的指向,使得在函数内部可以更方便地访问外部的 this。
-
模板字符串(Template Strings): 模板字符串允许使用
${}
语法插入变量和表达式到字符串中,使得字符串拼接更加直观和简洁。
const name = 'John';
console.log(`Hello, my name is ${name}.`); // 输出:Hello, my name is John.
- 解构赋值(Destructuring): 解构赋值允许从数组和对象中提取数据并赋值给变量,从而可以更方便地访问和使用数据。
const [a, b] = [1, 2];
const { x, y } = { x: 10, y: 20 };
- 类和继承(Classes and Inheritance): ES6 引入了类的概念,使得面向对象编程更加容易和直观,同时提供了更方便的继承机制。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Max');
dog.speak(); // 输出:Max barks.
- 模块化(Modules): ES6 提供了更好的模块化支持,允许将代码分割成独立的模块,并且可以在模块之间进行导入和导出,使得代码组织更加清晰和可维护。
// math.js
export function add(x, y) {
return x + y;
}
// app.js
import { add } from './math';
console.log(add(1, 2)); // 输出:3
- Promise 和 async/await: ES6 引入了 Promise 对象,提供了一种更好的异步编程方式,同时 ES8 引入了 async/await 关键字,使得异步代码更易于编写和理解。
function asyncFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Async operation completed');
}, 1000);
});
}
asyncFunction().then(result => {
console.log(result); // 输出:Async operation completed
});
// async/await 示例
async function asyncFunction() {
const result = await new Promise(resolve => {
setTimeout(() => {
resolve('Async operation completed');
}, 1000);
});
console.log(result); // 输出:Async operation completed
}
asyncFunction();
- 其他新特性:
The … Operator
For/of
Map Objects
Set Objects
Symbol
Default Parameters
Function Rest Parameter
String.includes()
String.startsWith()
String.endsWith()
Array.from()
Array keys()
Array find()
Array findIndex()
New Math Methods
New Number Properties
New Number Methods
New Global Methods
Object entries
… …