Home > Web Front-end > JS Tutorial > body text

A look at the five most important features of JavaScript ES6

coldplay.xixi
Release: 2020-06-23 12:45:13
forward
1964 people have browsed it

A look at the five most important features of JavaScript ES6

JavaScript ES6 adds a host of new language features, some more groundbreaking and more widely available than others. Features like ES6 classes, while novel, are really just syntactic sugar on top of the existing methods of creating classes in JavaScript. Functions like generators, although very powerful, are reserved for targeted tasks.

From working on different JavaScript-related projects over the past 12 months, I have found 5 ES6 features that are indispensable because they really simplify the way common JavaScript tasks are done. Your top 5 may be different from mine, and if so, I hope you'll share them in the comments section at the end.

Let’s get started!

  1. Arrow Functions
  2. Promises
  3. Async Functions
  4. Destructuring
  5. Default and Rest Parameters

1) JavaScript Arrow Function

One of my favorite new features in ES6 JavaScript is not a completely new feature. But a new syntax that makes me smile every time I use it. I'm talking about arrow functions, which provide an extremely elegant and concise way to define anonymous functions.

In short, the arrow function loses the keyword function, and then uses an arrow => to separate the parameter part and function body of an anonymous function :

(x, y) => x * y;
Copy after login

This is equivalent to:

function(x, y){
    return x * y;
}
Copy after login

or:

(x, y) => {
    var factor = 5;
    var growth = (x-y) * factor;
}
Copy after login

is exactly equivalent to:

function(x, y){
    var factor = 5;
    var growth = (x-y) * factor;
}
Copy after login

When using traditional anonymous functions, arrow functions It also eliminates a key source of errors, namely the value of the this object within a function. With arrow functions, this is based on lexical binding, which is just a fancy way of saying that its value is bound to the parent scope and never changes. If an arrow function is defined in a custom object countup, the this value will undoubtedly point to countup. For example:

var countup = {
    counter: 15,

    start:function(){
        window.addEventListener('click', () => {
            alert(this.counter) // correctly alerts 15 due to lexical binding of this
        })
    }
};

countup.start();
Copy after login

Compared with traditional anonymous functions, where the value of this changes depends on the context in which it is defined. When trying to reference this.counter in the above example, the result will be undefined, a behavior that may confuse many people who are not familiar with the complexities of dynamic binding. Using arrow functions, the value of this is always predictable and easy to infer.

For a detailed explanation of arrow functions, please see "Overview of JavaScript Arrow Functions".

2) JavaScript Promises

JavaScript ES6 Promises makes the processing of asynchronous tasks become Linear, this is a task in most modern web applications. Instead of relying on callback functions - popularized by JavaScript frameworks such as jQuery. JavaScript Promises use a central, intuitive mechanism for tracking and responding to asynchronous events. Not only does it make debugging asynchronous code easier, it also makes writing it a joy.

All JavaScript Promises start and end with the Promise() constructor:

const mypromise = new Promise(function(resolve, reject){
 // 在这编写异步代码
 // 调用 resolve() 来表示任务成功完成
 // 调用 reject() 来表示任务失败
})
Copy after login

Internally use resolve() and reject() method, when a Promise is completed or rejected, we can send a signal to a Promise object respectively. The then() and catch() methods can then be called to handle the work after the Promise is completed or rejected.

I use the following variant of Promise injected into the XMLHttpRequest function to retrieve the contents of external files one by one:

function getasync(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open("GET", url)
        xhr.onload = () => resolve(xhr.responseText)
        xhr.onerror = () => reject(xhr.statusText)
        xhr.send()
    })
}

getasync('test.txt').then((msg) => {
    console.log(msg) // echos contents of text.txt
    return getasync('test2.txt')
}).then((msg) => {
    console.log(msg) // echos contents of text2.txt
    return getasync('test3.txt')
}).then((msg) => {
    console.log(msg) // echos contents of text3.txt
})
Copy after login

To master the key points of JavaScript Promises, such as Promise chaining and parallel execution Promise, please read "Beginner's Guide to Promises".

3) JavaScript asynchronous functions

In addition to JavaScript Promise, asynchronous functions further rewrite the traditional asynchronous code structure to make it more readable sex. Whenever I show code with async programming capabilities to clients, the first reaction is always surprise, followed by curiosity to understand how it works.

An asynchronous function consists of two parts:

1) A regular function prefixed with async

async function fetchdata(url){
    // Do something
    // Always returns a promise
}
Copy after login

2) In the asynchronous function (Async function), use the await keyword to call the asynchronous operation function

An example is worth a thousand words. The following is a Promise rewritten based on the above example to use Async functions instead:

function getasync(url) { // same as original function
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open("GET", url)
        xhr.onload = () => resolve(xhr.responseText)
        xhr.onerror = () => reject(xhr.statusText)
        xhr.send()
    })
}

async function fetchdata(){ // main Async function
    var text1 = await getasync('test.txt')
    console.log(text1)
    var text2 = await getasync('test2.txt')
    console.log(text2)
    var text3 = await getasync('test3.txt')
    console.log(text3)
    return "Finished"
}

fetchdata().then((msg) =>{
    console.log(msg) // logs "finished"
})
Copy after login

When the above example is run, it will output "test.txt", "test2.txt", "test3 .txt" and finally "Finished".

As you can see, in the asynchronous function, we treat the asynchronous function getasync() as a synchronous function call – there is no then() method or callback function Notification to proceed to next step. Whenever the keyword await is encountered, execution is paused until getasync() resolves before moving to the next line in the async function. The result is the same as purely Promise-based, using a bunch of then methods.

要掌握异步函数,包括如何 await 并行执行函数,请阅读 “Introduction to JavaScript Async Functions- Promises simplified”

4) JavaScript 解构

除了箭头函数,这是我每天使用最多的 ES6 功能。ES6 解构并非一个新功能,而是一个新的赋值语法,可以让您快速解压缩对象属性和数组中的值,并将它们分配给各个变量。

var profile = {name:'George', age:39, hobby:'Tennis'}
var {name, hobby} = profile // destructure profile object
console.log(name) // "George"
console.log(hobby) // "Tennis"
Copy after login

这里我用解构快速提取 profile 对象的 namehobby 属性 。

使用别名,你可以使用与你正在提取值的对象属性不同的变量名:

var profile = {name:'George', age:39, hobby:'Tennis'}
var {name:n, hobby:h} = profile // destructure profile object
console.log(n) // "George"
console.log(h) // "Tennis"
Copy after login

嵌套对象解构

解构也可以与嵌套对象一起工作,我一直使用它来快速解开来自复杂的JSON请求的值:

var jsondata = {
    title: 'Top 5 JavaScript ES6 Features',
    Details: {
        date: {
            created: '2017/09/19',
            modified: '2017/09/20',
        },
        Category: 'JavaScript',
    },
    url: '/top-5-es6-features/'
};

var {title, Details: {date: {created, modified}}} = jsondata
console.log(title) // 'Top 5 JavaScript ES6 Features'
console.log(created) // '2017/09/19'
console.log(modified) // '2017/09/20'
Copy after login

解构数组

数组的解构与在对象上的工作方式类似,除了左边的花括号使用方括号代替:

var soccerteam = ['George', 'Dennis', 'Sandy']
var [a, b] = soccerteam // destructure soccerteam array
console.log(a) // "George"
console.log(b) // "Dennis"
Copy after login

你可以跳过某些数组元素,通过使用逗号(,):

var soccerteam = ['George', 'Dennis', 'Sandy']
var [a,,b] = soccerteam // destructure soccerteam array
console.log(a) // "George"
console.log(b) // "Sandy"
Copy after login

对我而言,解构消除了传统方式提取和分配对象属性和数组值的所有摩擦。要充分掌握ES6解构的复杂性和潜力,请阅读”Getting to Grips with ES6: Destructuring“.

5) 默认和剩余参数(Default and Rest Parameters)

最后,我最想提出的ES6的两个特性是处理函数参数。几乎我们在JavaScript中创建的每个函数都接受用户数据,所以这两个特性在一个月中不止一次地派上用场。

默认参数(Default Parameters)

我们都使用过一下模式来创建具有默认值的参数:

function getarea(w,h){
  var w = w || 10
  var h = h || 15
  return w * h
}
Copy after login

有了ES6对默认参数的支持,显式定义的参数值的日子已经结束:

function getarea(w=10, h=15){
  return w * h
}
getarea(5) // returns 75
Copy after login

关于 ES6 默认参数的更多详情 在这.

剩余参数(Rest Parameters)

ES6中的 Rest Parameters 使得将函数参数转换成数组的操作变得简单。

function addit(...theNumbers){
  // get the sum of the array elements
    return theNumbers.reduce((prevnum, curnum) => prevnum + curnum, 0) 
}

addit(1,2,3,4) // returns 10
Copy after login

通过在命名参数前添加3个点 ...,在该位置和之后输入到函数中的参数将自动转换为数组。

没有 Rest Parameters, 我们不得不做一些复杂的操作比如 手动将参数转换为数组 :

function addit(theNumbers){
    // force arguments object into array
    var numArray = Array.prototype.slice.call(arguments) 
    return numArray.reduce((prevnum, curnum) => prevnum + curnum, 0)
}

addit(1,2,3,4) // returns 10
Copy after login

Rest parameters 只能应用于函数的参数的一个子集,就像下面这样,它只会将参数从第二个开始转换为数组:

function f1(date, ...lucknumbers){
    return 'The Lucky Numbers for ' + date + ' are: ' + lucknumbers.join(', ')
}

alert( f1('2017/09/29', 3, 32, 43, 52) ) // alerts "The Lucky Numbers for 2017/09/29 are 3,32,43,52"
Copy after login

对于 ES6 中 Rest Parameters 完整规范,看这里.

结论

你同意我所说的 ES6 特性的前五名吗?哪个是你最常用的,请在评论区和大家分享。

推荐教程:《javascript基础教程

The above is the detailed content of A look at the five most important features of JavaScript ES6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:webhek.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template