Home  >  Article  >  Web Front-end  >  What does es6 come from?

What does es6 come from?

青灯夜游
青灯夜游Original
2022-04-11 13:54:163680browse

es6 was released in June 2015. The full name of es6 is "ECMAScript6". It is the JavaScript language standard officially released in June 2015. It is officially called ECMAScript2015 (ES2015). Because it is the 6th version of ECMAScript, it can be referred to as es6.

What does es6 come from?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

"es" introduction

es full name is "ECMAScript", which is a universal scripting language implemented according to the ECMA-262 standard, ECMA-262 standard It mainly stipulates the syntax, types, statements, keywords, reserved words, operators, objects and other parts of the language. The latest version of ECMAScript is currently ECMAScript6 (referred to as "ES6").

Every time you see ES followed by a number, it is a different version of ECMAScript.

es6/ ES2015

es6 stands for ECMAScript6 (the 6th version of ECMAScript). It is a JavaScript language officially released in June 2015. standard, officially called ECMAScript 2015 (ES2015). Its goal is to enable the JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language.

ECMAScript 6 has basically become the industry standard, and its popularity is much faster than ES5. The main reason is that modern browsers support ES6 very quickly, especially Chrome and Firefox browsers, which already support ES6. most features.

New features of ES6:

1. let, const and block scope

let allows creation of block level Scope, ES6 recommends using let to define variables in functions instead of var:

var a = 2;
{
  let a = 3;
  console.log(a); // 3
}
console.log(a); // 2

Another variable declaration method that is also valid in block-level scope is const, which can declare a constant. In ES6, a constant declared by const is similar to a pointer. It points to a reference, which means that this "constant" is not immutable, such as:

{
  const ARR = [5,6];
  ARR.push(7);
  console.log(ARR); // [5,6,7]
  ARR = 10; // TypeError
}

There are several points to note:

  • Variables declared with the let keyword do not have the variable hoisting feature
  • let and const declarations are only valid in the closest block (within curly braces)
  • When using constants When declaring const, please use uppercase variables, such as: CAPITAL_CASING
  • const must be assigned a value when declaring

2. Arrow Functions

In ES6, the arrow function is an abbreviation of the function, using parentheses to wrap the parameters, followed by =>, followed by the function body:

var getPrice = function() {
  return 4.55;
};
 
// Implementation with Arrow Function
var getPrice = () => 4.55;

It should be noted that in the above example The getPrice arrow function uses a concise function body, which does not require a return statement. The following example uses a normal function body:

let arr = ['apple', 'banana', 'orange'];
 
let breakfast = arr.map(fruit => {
  return fruit + 's';
});
 
console.log(breakfast); // apples bananas oranges

Of course, the arrow function not only makes the code simpler, this in the function is always The binding always points to the object itself. For details, you can look at the following examples:

function Person() {
  this.age = 0;
 
  setInterval(function growUp() {
    // 在非严格模式下,growUp() 函数的 this 指向 window 对象
    this.age++;
  }, 1000);
}
var person = new Person();

We often need to use a variable to save this, and then reference it in the growUp function:

function Person() {
  var self = this;
  self.age = 0;
 
  setInterval(function growUp() {
    self.age++;
  }, 1000);
}

Using arrow functions can save this trouble:

function Person(){
  this.age = 0;
 
  setInterval(() => {
    // |this| 指向 person 对象
    this.age++;
  }, 1000);
}
 
var person = new Person();

3. Default values ​​of function parameters

ES6 allows you to set default values ​​for function parameters:

let getFinalPrice = (price, tax=0.7) => price + price * tax;
getFinalPrice(500); // 850

4. Spread / Rest Operator

Spread / Rest operator refers to..., whether it is Spread or Rest depends on the context.

When used in an iterator, it is a Spread operator:

function foo(x,y,z) {
  console.log(x,y,z);
}
 
let arr = [1,2,3];
foo(...arr); // 1 2 3

When used to pass parameters in a function, it is a Rest operator:

function foo(...args) {
  console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

5. Object lexical extension

ES6 allows the use of shorthand syntax when declaring object literals to initialize the definition methods of attribute variables and functions, and allows calculation operations in object attributes:

function getCar(make, model, value) {
  return {
    // 简写变量
    make,  // 等同于 make: make
    model, // 等同于 model: model
    value, // 等同于 value: value
 
    // 属性可以使用表达式计算值
    ['make' + make]: true,
 
    // 忽略 `function` 关键词简写对象函数
    depreciate() {
      this.value -= 2500;
    }
  };
}
 
let car = getCar('Barret', 'Lee', 40000);
 
// output: {
//     make: 'Barret',
//     model:'Lee',
//     value: 40000,
//     makeBarret: true,
//     depreciate: [Function: depreciate]
// }

6. Binary and octal literals

ES6 supports binary and octal literals, which can be converted to octal by adding 0o or 0O in front of the number. Value:

let oValue = 0o10;
console.log(oValue); // 8
 
let bValue = 0b10; // 二进制使用 `0b` 或者 `0B`
console.log(bValue); // 2

7. Object and array destructuring

Destructuring can avoid the generation of intermediate variables during object assignment:

function foo() {
  return [1,2,3];
}
let arr = foo(); // [1,2,3]
 
let [a, b, c] = foo();
console.log(a, b, c); // 1 2 3
 
function bar() {
  return {
    x: 4,
    y: 5,
    z: 6
  };
}
let {x: x, y: y, z: z} = bar();
console.log(x, y, z); // 4 5 6

8. Object superclass

ES6 allows the use of the super method in objects:

var parent = {
  foo() {
    console.log("Hello from the Parent");
  }
}
 
var child = {
  foo() {
    super.foo();
    console.log("Hello from the Child");
  }
}
 
Object.setPrototypeOf(child, parent);
child.foo(); // Hello from the Parent
             // Hello from the Child

9. Template syntax and delimiters

There is one in ES6 A very neat way to assemble a bunch of strings and variables.

  • ${ ... } is used to render a variable
  • ` as the separator
let user = 'Barret';
console.log(`Hi ${user}!`); // Hi Barret!

10. for...of VS for...in

for...of is used to traverse an iterator, such as an array:

let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname of nicknames) {
  console.log(nickname);
}
// 结果: di, boo, punkeye

for...in is used to traverse the properties in an object:

let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname in nicknames) {
  console.log(nickname);
}
Result: 0, 1, 2, size

11. Map and WeakMap

There are two new sets of data structures in ES6: Map and WeakMap. In fact every object can be viewed as a Map.

An object consists of multiple key-val pairs. In Map, any type can be used as the key of the object, such as:

var myMap = new Map();
 
var keyString = "a string",
    keyObj = {},
    keyFunc = function () {};
 
// 设置值
myMap.set(keyString, "value 与 'a string' 关联");
myMap.set(keyObj, "value 与 keyObj 关联");
myMap.set(keyFunc, "value 与 keyFunc 关联");
 
myMap.size; // 3
 
// 获取值
myMap.get(keyString);    // "value 与 'a string' 关联"
myMap.get(keyObj);       // "value 与 keyObj 关联"
myMap.get(keyFunc);      // "value 与 keyFunc 关联"

WeakMap

WeakMap is a Map , but all its keys are weak references, which means that the things in WeakMap are not considered during garbage collection, so you don't have to worry about memory leaks when using it.

另一个需要注意的点是,WeakMap 的所有 key 必须是对象。它只有四个方法 delete(key),has(key),get(key) 和set(key, val):

let w = new WeakMap();
w.set('a', 'b'); 
// Uncaught TypeError: Invalid value used as weak map key
 
var o1 = {},
    o2 = function(){},
    o3 = window;
 
w.set(o1, 37);
w.set(o2, "azerty");
w.set(o3, undefined);
 
w.get(o3); // undefined, because that is the set value
 
w.has(o1); // true
w.delete(o1);
w.has(o1); // false

12. Set 和 WeakSet

Set 对象是一组不重复的值,重复的值将被忽略,值类型可以是原始类型和引用类型:

let mySet = new Set([1, 1, 2, 2, 3, 3]);
mySet.size; // 3
mySet.has(1); // true
mySet.add('strings');
mySet.add({ a: 1, b:2 });

可以通过 forEach 和 for...of 来遍历 Set 对象:

mySet.forEach((item) => {
  console.log(item);
    // 1
    // 2
    // 3
    // 'strings'
    // Object { a: 1, b: 2 }
});
 
for (let value of mySet) {
  console.log(value);
    // 1
    // 2
    // 3
    // 'strings'
    // Object { a: 1, b: 2 }
}

Set 同样有 delete() 和 clear() 方法。

WeakSet

类似于 WeakMap,WeakSet 对象可以让你在一个集合中保存对象的弱引用,在 WeakSet 中的对象只允许出现一次:

var ws = new WeakSet();
var obj = {};
var foo = {};
 
ws.add(window);
ws.add(obj);
 
ws.has(window); // true
ws.has(foo);    // false, foo 没有添加成功
 
ws.delete(window); // 从结合中删除 window 对象
ws.has(window);    // false, window 对象已经被删除

13. 类

ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继承模型,它只是原型链的语法糖表现形式。

函数中使用 static 关键词定义构造函数的的方法和属性:

class Task {
  constructor() {
    console.log("task instantiated!");
  }
 
  showId() {
    console.log(23);
  }
 
  static loadAll() {
    console.log("Loading all tasks..");
  }
}
 
console.log(typeof Task); // function
let task = new Task(); // "task instantiated!"
task.showId(); // 23
Task.loadAll(); // "Loading all tasks.."

类中的继承和超集:

class Car {
  constructor() {
    console.log("Creating a new car");
  }
}
 
class Porsche extends Car {
  constructor() {
    super();
    console.log("Creating Porsche");
  }
}
 
let c = new Porsche();
// Creating a new car
// Creating Porsche

extends 允许一个子类继承父类,需要注意的是,子类的constructor 函数中需要执行 super() 函数。

当然,你也可以在子类方法中调用父类的方法,如super.parentMethodName()。

在 这里 阅读更多关于类的介绍。

有几点值得注意的是:

  • 类的声明不会提升(hoisting),如果你要使用某个 Class,那你必须在使用之前定义它,否则会抛出一个 ReferenceError 的错误
  • 在类中定义函数不需要使用 function 关键词

14. Symbol

Symbol 是一种新的数据类型,它的值是唯一的,不可变的。ES6 中提出 symbol 的目的是为了生成一个唯一的标识符,不过你访问不到这个标识符:

var sym = Symbol( "some optional description" );
console.log(typeof sym); // symbol

注意,这里 Symbol 前面不能使用 new 操作符。

如果它被用作一个对象的属性,那么这个属性会是不可枚举的:

var o = {
    val: 10,
    [ Symbol("random") ]: "I'm a symbol",
};
 
console.log(Object.getOwnPropertyNames(o)); // val

如果要获取对象 symbol 属性,需要使用Object.getOwnPropertySymbols(o)。

15. 迭代器(Iterators)

迭代器允许每次访问数据集合的一个元素,当指针指向数据集合最后一个元素时,迭代器便会退出。它提供了 next() 函数来遍历一个序列,这个方法返回一个包含 done 和 value 属性的对象。

ES6 中可以通过 Symbol.iterator 给对象设置默认的遍历器,无论什么时候对象需要被遍历,执行它的 @@iterator 方法便可以返回一个用于获取值的迭代器。

数组默认就是一个迭代器:

var arr = [11,12,13];
var itr = arr[Symbol.iterator]();
 
itr.next(); // { value: 11, done: false }
itr.next(); // { value: 12, done: false }
itr.next(); // { value: 13, done: false }
 
itr.next(); // { value: undefined, done: true }

你可以通过 [Symbol.iterator]() 自定义一个对象的迭代器。

16. Generators

Generator 函数是 ES6 的新特性,它允许一个函数返回的可遍历对象生成多个值。

在使用中你会看到 * 语法和一个新的关键词 yield:

function *infiniteNumbers() {
  var n = 1;
  while (true){
    yield n++;
  }
}
 
var numbers = infiniteNumbers(); // returns an iterable object
 
numbers.next(); // { value: 1, done: false }
numbers.next(); // { value: 2, done: false }
numbers.next(); // { value: 3, done: false }

每次执行 yield 时,返回的值变为迭代器的下一个值。

17. Promises

ES6 对 Promise 有了原生的支持,一个 Promise 是一个等待被异步执行的对象,当它执行完成后,其状态会变成 resolved 或者rejected。

var p = new Promise(function(resolve, reject) {  
  if (/* condition */) {    // fulfilled successfully
    resolve(/* value */);  
  } else {    // error, rejected
    reject(/* reason */);  
  }});

每一个 Promise 都有一个 .then 方法,这个方法接受两个参数,第一个是处理 resolved 状态的回调,一个是处理 rejected 状态的回调:

p.then((val) => console.log("Promise Resolved", val),
       (err) => console.log("Promise Rejected", err));

【相关推荐:javascript视频教程web前端

The above is the detailed content of What does es6 come from?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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