ECMAScript 6:新颖吸引人功能的实用指南





5.00/5 (1投票)
本文旨在深入探讨 ECMAScript 6 引入的新功能,并提供开发人员如何使用它们的示例。
ECMAScript 6 - JavaScript 的最新标准化版本,于 2015 年 6 月通过。目前,ES6 的功能仅在现代浏览器中部分可用。在ES6 兼容性表中收集的有用信息反映了浏览器和转译器支持的新功能。
让我们来看看 10 项最重要的创新,尽管 ES6 提供了更多。要访问高级功能,您可以
- 使用支持 ECMAScript 6 的现代浏览器(例如 Google Chrome 版本 47),但请确保在 js 文件中添加“use strict”指令
- 通过安装Gulp-Babel 插件使用 ECMAScript 6
- 使用Babel转译器。在左侧输入 ECMAScript 6 代码,它将被转换为右侧的 ECMAScript 5。
让我们深入了解细节。
1. let 关键字
使用 let
关键字定义的变量有许多优点
- 这样定义的变量仅在该代码块内可见
- 在声明之前不能使用
let
变量
console.log(name); // error
let name = 'John';
通过在“for
”或“while
”循环中声明 let
变量,它仅在该循环本身内有效。对于 if
代码块也是如此。
for (let num = 5; num < 10; num++) {
console.log(num); // 5, 6, 7, 8, 9
}
console.log(num); // num is not defined
var number = 1;
if(number < 10) {
let v = 1;
v = v + 21;
v = v * 100;
v = v / 8;
console.log(v);
}
console.log(v); //v is not defined
请注意,禁止声明两次 let
变量。以下示例会导致错误
let name;
let name; // error
2. 类
在早期版本的 JavaScript 中,要描述一个类,需要写如下代码
function Product(price, category, description) {
this.price = price;
this.category = category;
this.description = description;
this.isPublished = false;
}
Product.prototype.publish = function publish() {
this.isPublished = true;
};
Product.prototype.unpublish = function unpublish() {
this.isPublished = false;
};
在 ECMAScript 6 中,要声明一个类,应该使用 class 和 constructor 关键字。现在您还可以使用“class Child extends Parent
”语法继承新类,这可能对您来说很熟悉,因为您可能了解其他面向对象编程语言(例如 PHP)。Static
方法也可以在类中声明。让我们以以下示例为例来说明这一声明
class Product {
constructor(price, category, description) {
this.price = price;
this.category = category;
this.description = description;
this.isPublished = false;
}
publish() {
this.isPublished = true;
}
unpublish() {
this.isPublished = false;
}
static getDate() {
return new Date();
}
}
class DownlowdableProduct extends Product{
// your code goes here
}
要创建类的实例,您可以使用 new
关键字。
3. 默认值
ES6 引入了为参数设置默认值的可能性。此功能的语法不言自明。默认值在调用函数时指定。这是一个示例,其中 isPublished
默认设置
class Product {
constructor(price, category, description, isPublished = false) {
this.price = price;
this.category = category;
this.description = description;
this.isPublished = isPublished;
}
publish() {
this.isPublished = true;
}
unpublish() {
this.isPublished = false;
}
}
表达式可以设置为参数的默认值。
function sayHello(name = getCurrentUser().toUpperCase()) {
console.log('Hello, ' + name);
}
function getCurrentUser() {
return 'Guest';
}
sayHello();
4. const 关键字
要声明一个常量,您可以使用 const
关键字,从而创建一个不可更改的变量
const MAX_NUM = 5;
MAX_NUM = 10; // error
请注意,如果将对象分配给常量,您不能更改该常量本身,但可以修改其中的属性。这同样适用于数组或其他对象值。
const person = {
screenName: "Guest"
};
person.screenName = "John"; // available
person = 5; // error
5. 模板字符串
ECMAScript 6 有一种指定模板 string
s 的新方法:它们以反引号(`)开头和结尾。
let string = `New String`;
如果您使用单引号和双引号,则允许使用新行并使用花括号 ${variable}
替换表达式。
class Product {
constructor(price, description, isPublished = false) {
this.price = price;
this.description = description;
this.isPublished = isPublished;
}
publish() {
this.isPublished = true;
}
unpublish() {
this.isPublished = false;
}
}
class DownlowdableProduct extends Product {
constructor(price, link, title, description, isPublished = false) {
super(price, description, isPublished);
this.link = link;
this.title = title;
}
toString() {
return `<li>
${this.title} - ${this.link} <span>${this.price}</span>
</li>`;
}
}
6. 解构赋值
解构赋值是从(可能嵌套的)对象和数组中提取值的便捷方法。它可以在接收数据的任何位置使用(例如,赋值的左侧)。
var [firstName, lastName, city] = ["John", "Doe", "Moscow"];
因此,firstName
包含“John
”,lastName
包含“Doe
”,city
包含“Moscow
”。
如果您想丢弃不需要的项,则需要添加一个额外的逗号
let [, , lastName] = "Hello John Doe".split(" "); // first and second elements will be ignored
console.log(lastName); // Doe
对于对象,代码如下
var contact = {
email: "john@mail.com",
url: "http://google.com"
}
var {email, url} = contact;
此代码与以下代码类似
var contact = {
email: "john@mail.com",
url: "http://google.com"
};
var email = contact.email;
var url = contact.url;
您可以轻松地将数组或对象拆分为变量,而这些数组或对象本身又包含其他数组或对象。
let settings = {
params: {
w: 100,
h: 200
},
elements: ["Home", "Contact Us"]
}
let { title="Menu", params: {w, h}, elements: [item1, item2] } = settings;
console.log(title); // Menu
console.log(w); // 100
console.log(h); // 200
console.log(item1); // Home
console.log(item2); // Contact Us
7. 对象字面量
考虑一个典型的 JavaScript 示例
function makeRequest(method, url) {
return {
method: method,
url: url
}
}
在调用 makeRequest
函数时,将使用 method 和 url 键创建对象字面量。在 ECMAScript 6 中,同样的事情可以用更简洁的方式完成
function makeRequest(method, url) {
return {
method,
url
}
}
8. Symbols (符号)
Symbol
- 一种数据类型,类似于 Number
和 String
,可用于生成唯一标识符。每个符号都是唯一的。
let unique = Symbol(‘sym’);
请注意,Symbol
在不使用 new
关键字的情况下使用,因为它是一种原始类型。此函数可用于创建唯一常量。
const FIRST = Symbol('my symbol');
const SECOND = Symbol('my symbol');
typeof FIRST === 'symbol'; // true
FIRST === SECOND; // false
可选参数描述可用于描述符号,并有助于调试
let unique = Symbol("sym"); console.log( unique.toString() ); // Symbol(sym)
9. Rest & Spread (剩余参数 & 展开语法)
要获取参数数组,可以使用...运算符,如下所示
function printInfo(first, last, ...other) {
console.log(first + ' ' + last + ' - ' + other);
}
printInfo("John", "Doe", "student"); // John Doe - student
在 other
中将写入一个参数数组,从第二个参数开始。可以看到 other
是一个普通数组,可以使用标准方法,如 map
、forEach
和 other
,这些方法对于 arguments 伪数组不可用。
…运算符必须始终放在最后,并可用于读取函数声明中的参数。在调用函数时也可以使用它,以列表形式传递参数数组
let nums = [9, 3, 20];
let maxNumber = Math.max(...nums);
console.log( maxNumber ); // 20
10. 箭头函数
让我们看下面的例子
class Contact {
constructor(attachment, mail, sender) {
this.attachment = attachment;
this.mail = mail;
sender.onclick = function(event) {
sendEmail(this.mail);
}
}
}
当我按下按钮时,我希望使用 sendEmail
函数并将其 this.mail
参数传递过去。但这将在发送者的上下文中被使用,而不是 Contact
的上下文中。有些人会将此变量分配到作用域之外
class Contact {
constructor(attachment, mail, sender) {
this.attachment = attachment;
this.mail = mail;
var that = this;
sender.onclick = function(event) {
sendEmail(that.mail);
}
}
}
有一种创建函数的新方法,使用箭头
class Contact {
constructor(attachment, mail, sender) {
this.attachment = attachment;
this.mail = mail;
sender.onclick = (event) => {
sendEmail(this.mail);
}
}
}
这样,就可以创建简单的函数。
var numArray = [2,4,6,8,10];
var newNumArray = numArray.map((elem) => elem * 2);
console.log(newNumArray); // [4,8,12,16,20]
结论
ECMAScript 6 的支持仍然非常有限,许多功能仍在开发中。但很快,就可以充分利用这些功能了。