-
箭头函数 (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`
-
模板字符串 (Template Literals)
javascript``// ES5 字符串拼接
var name = "Alice";
var greeting = "Hello, " + name + "!";// ES6 模板字符串
let name = "Alice";
let greeting =Hello, ${name}!
;console.log(greeting); // 输出 "Hello, Alice!"``
-
解构赋值 (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` -
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);
});` -
类 (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)、默认参数、剩余参数、展开操作符等。