ES2017指南

ECMAScript 2017, edition 8 of the ECMA-262 Standard (also commonly called ES2017 or ES8), was finalized in June 2017.

ECMAScript 2017,ECMA-262标准的第8版(也通常称为ES2017ES8 )已于2017年6月完成。

Compared to ES6, ES8 is a tiny release for JavaScript, but still it introduces very useful features:

与ES6相比,ES8是一个很小JavaScript版本,但仍引入了非常有用的功能:

  • String padding

    字符串填充
  • Object.values()

    Object.values()

  • Object.entries()

    Object.entries()

  • Object.getOwnPropertyDescriptors()

    Object.getOwnPropertyDescriptors()

  • Trailing commas in function parameter lists and calls

    函数参数列表和调用中的尾部逗号
  • Async functions

    异步功能
  • Shared memory and atomics

    共享内存和原子

字符串填充 (String padding)

The purpose of string padding is to add characters to a string, so it reaches a specific length.

字符串填充的目的是在字符串中添加字符 ,使其达到特定长度

ES2017 introduces two String methods: padStart() and padEnd().

ES2017引入了两个String方法: padStart()padEnd()

padStart(targetLength [, padString])
padEnd(targetLength [, padString])

Sample usage:

用法示例:

padStart()
‘test’.padStart(4)‘test’
‘test’.padStart(5)‘ test’
‘test’.padStart(8)‘    test’
‘test’.padStart(8, ‘abcd’)‘abcdtest’
padStart()
'test'.padStart(4) '测试'
'test'.padStart(5) '测试'
'test'.padStart(8) '测试'
'test'.padStart(8,'abcd') 'abcdtest'
padEnd()
‘test’.padEnd(4)‘test’
‘test’.padEnd(5)‘test ‘
‘test’.padEnd(8)‘test    ‘
‘test’.padEnd(8, ‘abcd’)‘testabcd’
padEnd()
'test'.padEnd(4) '测试'
'test'.padEnd(5) '测试'
'test'.padEnd(8) '测试'
'test'.padEnd(8,'abcd') 'testabcd'

Object.values() (Object.values())

This method returns an array containing all the object own property values.

此方法返回一个包含所有对象自身属性值的数组。

Usage:

用法:

const person = { name: 'Fred', age: 87 }
Object.values(person) // ['Fred', 87]

Object.values() also works with arrays:

Object.values()也可用于数组:

const people = ['Fred', 'Tony']
Object.values(people) // ['Fred', 'Tony']

Object.entries() (Object.entries())

This method returns an array containing all the object own properties, as an array of [key, value] pairs.

此方法以[key, value]对的数组形式返回一个包含所有对象自身属性的数组。

Usage:

用法:

const person = { name: 'Fred', age: 87 }
Object.entries(person) // [['name', 'Fred'], ['age', 87]]

Object.entries() also works with arrays:

Object.entries()也可用于数组:

const people = ['Fred', 'Tony']
Object.entries(people) // [['0', 'Fred'], ['1', 'Tony']]

getOwnPropertyDescriptors() (getOwnPropertyDescriptors())

This method returns all own (non-inherited) properties descriptors of an object.

此方法返回对象的所有自己的(非继承)属性描述符。

Any object in JavaScript has a set of properties, and each of these properties has a descriptor.

JavaScript中的任何对象都有一组属性,并且每个属性都有一个描述符。

A descriptor is a set of attributes of a property, and it’s composed by a subset of the following:

描述符是属性的一组属性,由以下子集组成:

  • value: the value of the property

    :属性的值

  • writable: true the property can be changed

    可写 :true可以更改属性

  • get: a getter function for the property, called when the property is read

    get :属性的getter函数,在读取属性时调用

  • set: a setter function for the property, called when the property is set to a value

    set :属性的setter函数,在将属性设置为值时调用

  • configurable: if false, the property cannot be removed nor any attribute can be changed, except its value

    可配置的 :如果为false,则不能删除该属性,也不能更改任何属性,但其值除外

  • enumerable: true if the property is enumerable

    枚举 :如果属性是可枚举的,则为true

Object.getOwnPropertyDescriptors(obj) accepts an object, and returns an object with the set of descriptors.

Object.getOwnPropertyDescriptors(obj)接受一个对象,并返回带有描述符集的对象。

这有什么用处? (In what way is this useful?)

ES6 gave us Object.assign(), which copies all enumerable own properties from one or more objects, and return a new object.

ES6给了我们Object.assign() ,它从一个或多个对象复制了所有可枚举的自身属性,并返回一个新对象。

However there is a problem with that, because it does not correctly copies properties with non-default attributes.

但是,这有一个问题,因为它不能正确复制具有非默认属性的属性。

If an object for example has just a setter, it’s not correctly copied to a new object, using Object.assign().

例如,如果某个对象只有一个setter,则无法使用Object.assign()将其正确复制到新对象。

For example with

例如与

const person1 = {
    set name(newName) {
        console.log(newName)
    }
}

This won’t work:

这行不通:

const person2 = {}
Object.assign(person2, person1)

But this will work:

但这将起作用:

const person3 = {}
Object.defineProperties(person3,
  Object.getOwnPropertyDescriptors(person1))

As you can see with a simple console test:

您可以通过简单的控制台测试看到:

person1.name = 'x'
"x"

person2.name = 'x'

person3.name = 'x'
"x"

person2 misses the setter, it was not copied over.

person2错过了设置者,它没有被复制。

The same limitation goes for shallow cloning objects with Object.create().

同样的限制也适用于使用Object.create()进行浅层克隆的对象。

尾随逗号 (Trailing commas)

This feature allows to have trailing commas in function declarations, and in functions calls:

此功能允许在函数声明和函数调用中使用逗号结尾:

const doSomething = (var1, var2,) => {
  //...
}

doSomething('test2', 'test2',)

This change will encourage developers to stop the ugly “comma at the start of the line” habit.

这种变化将鼓励开发人员停止丑陋的“逗号开头”习惯。

异步功能 (Async functions)

Check the dedicated post about async/await

查看有关异步/等待的专用帖子

ES2017 introduced the concept of async functions, and it’s the most important change introduced in this ECMAScript edition.

ES2017引入了异步函数的概念,这是此ECMAScript版本中引入的最重要的变化。

Async functions are a combination of promises and generators to reduce the boilerplate around promises, and the “don’t break the chain” limitation of chaining promises.

异步功能是promise和生成器的组合,可减少promise的样板,以及链接promise的“请勿打破链条”限制。

为什么它们有用 (Why they are useful)

It’s a higher level abstraction over promises.

这是对诺言的更高层次的抽象。

When Promises were introduced in ES6, they were meant to solve a problem with asynchronous code, and they did, but over the 2 years that separated ES6 and ES2017, it was clear that promises could not be the final solution. Promises were introduced to solve the famous callback hell problem, but they introduced complexity on their own, and syntax complexity. They were good primitives around which a better syntax could be exposed to the developers: enter async functions.

当将Promises引入ES6时,它们旨在解决异步代码的问题,并且确实做到了,但是在将ES6和ES2017分开的两年中,很明显, 诺言不可能成为最终的解决方案 。 引入了承诺来解决著名的回调地狱问题,但是它们自己引入了复杂性以及语法复杂性。 它们是很好的原语,可以为开发人员提供更好的语法:输入异步函数

一个简单的例子 (A quick example)

Code making use of asynchronous functions can be written as

利用异步功能的代码可以写成

function doSomethingAsync() {
    return new Promise((resolve) => {
        setTimeout(() => resolve('I did something'), 3000)
    })
}

async function doSomething() {
    console.log(await doSomethingAsync())
}

console.log('Before')
doSomething()
console.log('After')

The above code will print the following to the browser console:

上面的代码会将以下内容打印到浏览器控制台:

Before
After
I did something //after 3s

多个异步功能串联 (Multiple async functions in series)

Async functions can be chained very easily, and the syntax is much more readable than with plain promises:

异步函数可以很容易地链接起来,并且语法比普通的诺言更具可读性:

function promiseToDoSomething() {
    return new Promise((resolve)=>{
        setTimeout(() => resolve('I did something'), 10000)
    })
}

async function watchOverSomeoneDoingSomething() {
    const something = await promiseToDoSomething()
    return something + ' and I watched'
}

async function watchOverSomeoneWatchingSomeoneDoingSomething() {
    const something = await watchOverSomeoneDoingSomething()
    return something + ' and I watched as well'
}

watchOverSomeoneWatchingSomeoneDoingSomething().then((res) => {
    console.log(res)
})

共享内存和原子 (Shared Memory and Atomics)

WebWorkers are used to create multithreaded programs in the browser.

WebWorkers用于在浏览器中创建多线程程序。

They offer a messaging protocol via events. Since ES2017, you can create a shared memory array between web workers and their creator, using a SharedArrayBuffer.

它们通过事件提供消息传递协议。 自ES2017起,您可以使用SharedArrayBufferWeb Worker及其创建者之间创建共享内存阵列。

Since it’s unknown how much time writing to a shared memory portion takes to propagate, Atomics are a way to enforce that when reading a value, any kind of writing operation is completed.

由于不知道写入共享内存部分需要花费多少时间才能传播,因此Atomics是一种在读取值时强制执行任何类型的写入操作的方法。

Any more detail on this can be found in the spec proposal, which has since been implemented.

有关此规范的更多详细信息,请参见规范建议 ,此建议已实施。

翻译自: https://flaviocopes.com/es2017/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值