科技和互联网

ES8发布了,了解下新特性

今年六月底,ES8发布了。ES8又名ES2017,从2009年Javascript冉冉升起时,ES5开始发布,到现在是ES8了,这里介绍几个重要的特性,当然,达人可以阅读官方PDF文档。字符填充(String Padding),用padStart,padEnd从字符串两端填充空格或第二个参数(字符串)。对象值函数,Object.values返回数组,对象记录函数,Object.entries返回字典。Object.getOwnPropertyDescriptors这个函数名也很直观,主要用于decorator。跟踪多余逗点功能,防止编译报错。还有异步函数(Async functions),等等。不断更新的Javascript看来注定要两头通吃了。

原文链接:https://hackernoon.com

抄录:

ES8 was Released and Here are its Main New Features

By Dor Moshe July 10th, 2017
The new features of the EcmaScript specification 8th edition

 

EcmaScript 8 or EcmaScript 2017 was officially released in the end of June by TC39. It seems that we are talking a lot about EcmaScript in the last year. It’s not for nothing. Currently the standard is to publish a new ES specification version once a year. ES6 was published in 2015 and ES7 was published in 2016, but did someone remembered when ES5 was released? It was happened in 2009, before the magical rise of JavaScript.

So we follow after the changes in the developing of JavaScript as stable language and now we need to enter ES8 to our lexicon.

 

If you are a strong people, take a deep breath and read the web or PDF edition of the specification. For the others, in this article we will cover the main new features of ES8 by code examples.

String padding
This section adds two functions to the String object: padStart & padEnd.
As their names, the purpose of those functions is to pad the start or the end of the string, so that the resulting string reaches the given length. You can pad it with specific character or string or just pad with spaces by default. Here are the functions declaration:

str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])
As you can see, the first parameter of those functions is the targetLength, that is the total length of the resulted string. The second parameter is the optional padString that is the string to pad the source string. The default value is space.

‘es8’.padStart(2); // ‘es8’
‘es8’.padStart(5); // ‘ es8’
‘es8’.padStart(6, ‘woof’); // ‘wooes8’
‘es8’.padStart(14, ‘wow’); // ‘wowwowwowwoes8’
‘es8’.padStart(7, ‘0’); // ‘0000es8’
‘es8’.padEnd(2); // ‘es8’
‘es8’.padEnd(5); // ‘es8 ‘
‘es8’.padEnd(6, ‘woof’); // ‘es8woo’
‘es8’.padEnd(14, ‘wow’); // ‘es8wowwowwowwo’
‘es8’.padEnd(7, ‘6’); // ‘es86666’

Browser support
Photo by: MDN
Object.values and Object.entries
The Object.values method returns an array of a given object’s own enumerable property values, in the same order as that provided by a for in loop. The declaration of the function is trivial:

Object.values(obj)
The obj parameter is the source object for the operation. It can be an object or an array (that is an object with indexes like [10, 20, 30] -> { 0: 10, 1: 20, 2: 30 }).

const obj = { x: ‘xxx’, y: 1 };
Object.values(obj); // [‘xxx’, 1]

const obj = [‘e’, ‘s’, ‘8’]; // same as { 0: ‘e’, 1: ‘s’, 2: ‘8’ };
Object.values(obj); // [‘e’, ‘s’, ‘8’]

// when we use numeric keys, the values returned in a numerical
// order according to the keys
const obj = { 10: ‘xxx’, 1: ‘yyy’, 3: ‘zzz’ };
Object.values(obj); // [‘yyy’, ‘zzz’, ‘xxx’]

Object.values(‘es8’); // [‘e’, ‘s’, ‘8’]

Browser support
Photo by: MDN
The Object.entries method returns an array of a given object’s own enumerable property [key, value] pairs, in the same order as Object.values. The declaration of the function is trivial:

const obj = { x: ‘xxx’, y: 1 };
Object.entries(obj); // [[‘x’, ‘xxx’], [‘y’, 1]]
const obj = [‘e’, ‘s’, ‘8’];
Object.entries(obj); // [[‘0’, ‘e’], [‘1’, ‘s’], [‘2’, ‘8’]]

const obj = { 10: ‘xxx’, 1: ‘yyy’, 3: ‘zzz’ };
Object.entries(obj); // [[‘1’, ‘yyy’], [‘3’, ‘zzz’], [’10’: ‘xxx’]]

Object.entries(‘es8’); // [[‘0’, ‘e’], [‘1’, ‘s’], [‘2’, ‘8’]]

Browser support
Photo by: MDN
Object.getOwnPropertyDescriptors
The getOwnPropertyDescriptors method returns the own property descriptor of the specified object. An own property descriptor is one that is defined directly on the object and is not inherited from the object’s prototype. The declaration of the function is:

Object.getOwnPropertyDescriptor(obj, prop)
The obj is the source object and prop is the object’s property name whose description is to be retrieved. The possible keys for the result are configurable, enumerable, writable, get, set and value.

const obj = { get es8() { return 888; } };
Object.getOwnPropertyDescriptor(obj, ‘es8’);
// {
// configurable: true,
// enumerable: true,
// get: function es8(){}, //the getter function
// set: undefined
// }
The descriptor data is very important for advanced features like decorators.

 

Browser support
Photo by: MDN
Trailing commas in function parameter lists and calls
Trailing commas in function parameter is the ability of the compiler not to raise an error (SyntaxError) when we add unnecessary comma in the end of the list:

function es8(var1, var2, var3,) {
// …
}
As the function declaration, this can be applied on function’s calls:

es8(10, 20, 30,);
This feature inspired from the trailing of commas in object literals and Array literals [10, 20, 30,] and { x: 1, }.

Async functions
The async function declaration defines an asynchronous function, which returns an AsyncFunction object. Internally, async functions work much like generators, but they are not translated to generator functions.

function fetchTextByPromise() {
return new Promise(resolve => {
setTimeout(() => {
resolve(“es8”);
}, 2000));
});
}
async function sayHello() {
const externalFetchedText = await fetchTextByPromise();
console.log(Hello, ${externalFetchedText}); // Hello, es8
}
sayHello();
The call of sayHello will log Hello, es8 after 2 seconds.

console.log(1);
sayHello();
console.log(2);
And now the prints are:

1 // immediately
2 // immediately
Hello, es8 // after 2 seconds
This is because the function call doesn’t block the flow.

Pay attention that an async function always returns a promise and an await keyword may only be used in functions marked with the async keyword.

 

Browser support
Photo by: MDN
Shared memory and atomics
When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. This section introduces a new constructor SharedArrayBuffer and a namespace object Atomics with static methods.

The Atomic object is an object of static methods like Math, so we can’t use it as a constructor. Examples for static method in this object are:

add / sub— add / subtract a value for the value at a specific position
and / or / xor — bitwise and / bitwise or / bitwise xor
load — get the value at a specific position

Browser support
Photo by: MDN
And one for the next year in ES9 — Lifting template literal restriction
With the tagged template literal (ES6) we can do stuff like declaring a template parsing function and returning a value according to our logic:

const esth = 8;
helperES ${esth} is;
function helper(strs, …keys) {
const str1 = strs[0]; // ES
const str2 = strs[1]; // is
let additionalPart = ”;
if (keys[0] == 8) { // 8
additionalPart = ‘awesome’;
}
else {
additionalPart = ‘good’;
}
return ${str1} ${keys[0]} ${str2} ${additionalPart}.;
}

The returned value will be → ES 8 is awesome.
And for esth of 7 the returned value will be → ES 7 is good.

But there is a restriction for templates that contain for example \u or \x sub strings. ES9 will deal with this escaping problem. Read more about it in the MDN website or in the TC39 document.

 

Browser support
Photo by: MDN
Conclusion
JavaScript is in production, but it is always get renewed. The process of adopting new features to the specification is very arranged and poised. In the last stage, these features confirmed by the TC39 committee and implemented by the core developers. Most of them are already parts of the Typescript language, browsers or other polyfills, so you can go and try them right now.

Tagged

我忍不住要留言