JavaScript ES6 (也称为 ECMAScript2015 或 ECMAScript6) 是于 2015 年 6 月推出的第六版 JavaScript。
ECMAScript (European Computer Manufacturers Association Script) 是 JavaScript 的标准规范,以确保在所有浏览器和环境中兼容。
本教程总结了 ES6 中常用的功能和语法改进。
JavaScript 声明
以前,JavaScript 只允许使用 var
关键字声明变量。
ES6 现在允许您使用另外两个关键字声明变量:let
和 const
。
使用 let 关键字声明
let
关键字创建 块级作用域 变量,这意味着它们只能在特定的代码块中访问。例如,
{
// block of code
// declare variable with let
let name = "Peter";
// can be accessed here
console.log(name); // Peter
}
// can't be accessed here
console.log(name);
输出
Peter ERROR! ... ReferenceError: name is not defined
但是,如果我们用 var
替换 let
,则上述程序可以正常运行。例如,
{
// block of code
// declare variable with var
var name = "Peter";
// can be accessed here
console.log(name);
}
// can be accessed here
console.log(name);
输出
Peter Peter
这仅仅意味着我们可以更好地控制使用 let
声明的变量。
要了解 let
和 var
之间的区别,请访问 JavaScript let vs var。
使用 const 关键字声明
const
关键字创建常量变量,这些变量在声明后不能更改。例如,
// declare variable with const
const fruit = "Apple";
console.log(fruit);
// reassign fruit
// this code causes an error
fruit = "Banana";
console.log(fruit);
输出
Apple Error: Assignment to constant variable
在这里,我们使用 const
声明变量 fruit,其值为 Apple
。
因此,将其值更改为 Banana
会导致错误。
JavaScript 模板字面量
模板字面量使得在字符串中包含变量更加容易。
例如,这是我们之前连接字符串和变量的方式
const firstName = "Jack";
const lastName = "Sparrow";
console.log("Hello " + firstName + " " + lastName);
// Output: Hello Jack Sparrow
现在,您只需这样做即可
const firstName = "Jack";
const lastName = "Sparrow";
console.log(`Hello ${firstName} ${lastName}`);
// Output: Hello Jack Sparrow
要了解更多关于模板字面量的信息,请访问 JavaScript Template Literal。
默认参数值
在 ES6 中,您可以为函数参数传递默认值。例如,
// function to find sum of two numbers
function sum(numA, numB = 5) {
// default value of numB is 5
console.log(numA + numB);
};
// pass 10 to numA but
// don't pass value to numB
// numB takes default value 5
sum(10); // 15
// pass 5 to numA and 15 to numB
sum(5, 15); // 20
在上面的示例中,我们在函数声明中包含了默认参数值 numB = 5
。
这意味着,即使您不为 numB 传递参数,它也将默认使用 5。
要了解更多关于默认参数的信息,请访问 JavaScript Default Parameters。
JavaScript 箭头函数
ES6 引入了一种使用 =>
编写 函数和函数表达式 的新方法,称为箭头函数。
以前,编写函数表达式的唯一方法是
// function expression
let product = function(x, y) {
return x * y;
};
result = product(5, 10);
console.log(result); // 50
现在,您只需这样写即可
// function expression using arrow function
let product = (x, y) => x * y;
result = product(5, 10);
console.log(result); // 50
要了解更多关于箭头函数的信息,请访问 JavaScript Arrow Function。
JavaScript 类
ES6 还引入了类(面向对象编程 (OOP) 的基本方面)的概念。
我们可以使用 class
关键字创建类和对象。以前,我们使用 构造函数 来创建对象。例如,
// constructor function
function Person(name) {
this.name = name;
};
// create objects
var p1 = new Person("John");
var p2 = new Person("Rachel");
// print object properties
console.log(p1.name); // John
console.log(p2.name); // Rachel
现在,我们可以使用 class
关键字完成相同的事情。并且,我们可以使用 constructor()
函数初始化类。例如,
// declare a class
class Person {
// constructor function
constructor(name) {
this.name = name;
};
};
// create objects
let p1 = new Person("John");
let p2 = new Person("Rachel");
// print object properties
console.log(p1.name); // John
console.log(p2.name); // Rachel
要了解更多关于类的信息,请访问 JavaScript Classes。
JavaScript 解构
解构语法使得从数组或对象中提取值到单独的变量更加容易。
例如,以前我们提取对象值到变量的方式如下
// object of hospital
const hospital = {
doctors: 23,
patients: 44,
};
// assign individual values
let doctors = hospital.doctors;
let patients = hospital.patients;
console.log(doctors); // 23
console.log(patients); // 44
现在,我们只需使用 ES6 解构语法即可
const hospital = {
doctors: 23,
patients: 44,
};
// use ES6 destructuring syntax
let { doctors, patients } = hospital;
console.log(doctors); // 23
console.log(patients); // 44
要了解更多关于解构的信息,请访问 JavaScript Destructuring。
JavaScript import 和 export
在 ES6 之前,没有标准的方法供开发人员将代码管理在单独的文件中作为模块。
有了 ES6,我们终于可以使用 import
和 export
语法来管理模块了。
例如,假设您有两个名为 person.js 和 action.js 的 JavaScript 文件。
在 action.js 中,您可以导出任何内容。在本教程中,我们只导出一个名为 greet()
的函数
// export
export default function greet(name) {
console.log(`Hi ${name}!`);
};
然后,在 person.js 中,您可以导入 greet()
函数并使用它
import greet from './action.js';
greet("Sara");
// Output: Hi Sara!
JavaScript Promise
ES6 Promise
提供了一种处理 异步任务 的简洁方法。例如,
// define a promise
let countValue = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Promise resolved!");
}, 5000);
});
// executes when promise resolves
countValue.then(function successValue(result) {
console.log(result);
});
// Output: Promise resolved!
在这里,我们首先在变量 countValue 上创建了一个 Promise。
然后,我们使用 setTimeout()
函数在延迟 5 秒后解析该 Promise。
同样,当 Promise 解析时,.then()
方法会执行并显示输出 Promise resolved!
。
要了解更多关于 Promise 的信息,请访问 JavaScript Promises。
JavaScript Rest 参数
您可以使用 **rest** **参数** ...
将任意数量的参数表示为一个数组。例如,
// function with ...args rest parameter
function show(a, b, ...args) {
console.log("a:", a);
console.log("b:", b);
console.log("args:", args);
}
// call function with extra parameters
show(1, 2, 3, 4, 5);
输出
a: 1 b: 2 args: [ 3, 4, 5 ]
您可以使用任何名称作为 rest 参数。但是,args 是一个常见的约定。
展开运算符
您可以使用 **展开运算符** ...
来展开数组或对象。例如,
let numArr = [1, 2, 3];
// without spread operator
console.log([numArr, 4, 5]); // [[1, 2, 3], 4, 5]
// with spread operator
console.log([...numArr, 4, 5]); // [1, 2, 3, 4, 5]
要了解更多关于展开运算符的信息,请访问 JavaScript Spread Operator.。
注意: rest 参数和展开运算符都使用相同的语法。但是,我们只在函数定义中将 rest 参数用作参数。