What are the characteristics of ES6 worth learning?

What are the characteristics of ES6 worth learning?

Diligence neglected in play
Insert picture description here

01 Preface


ES6 is now the next-generation language standard. Front-end learning has reached a new stage. Our JavaScript language can already be used to write complex large-scale applications and become an enterprise-level development language. And the front-end development position is now one of the most important positions in the enterprise, so it is a matter of course to learn new technologies and drive products with technology.

For the study of ES6, we suggest to take a look at Mr. Ruan Yifeng ’s tutorial, which details every knowledge point, which is very easy to understand. Next, I will talk about some of the more important features that ES6 has added, which can be used in our projects and interview the frequently asked questions.

02 New features


Many new features have been added to ES6, and it is impossible to elaborate on each one here. I encountered the following in the interview. You can pass it if you describe them clearly.

  • The difference between let, var and const
  • Arrow function
  • Destructuring assignment
  • Template string
  • Set, Map data structure
  • Promise object
  • Proxy
The difference between let, var, and const

These are all keywords used to declare variables / constants. In the past, we generally used var to declare, but there are some disadvantages and it is easy to make mistakes.

Let us first understand the problem of variable promotion and scope.

Variable promotion: when you use var for declaration, you can use it without declaration. such as:

console.log(a); //undefined

Will the function improve? Which function or variable has higher priority?

console.log(a);  //f (a){}
var a=1;
function a(){};

The result we get is that the function has higher priority than the variable. So what is the scope?

var a=1;
function b(){
  var a=2
  console.log(a);
}
b()

Execution of this code, we will get the result is 2

var a = 1;
function b() {
    // var a = 2
    console.log(a);
}
b()

But when we comment the code, we will find that the result becomes 1.

Scope: When you can't find a statement in the current job domain, you will go to the parent's scope to find it. This way, you will find the chain progressively and eventually form a chain. This is the scope chain.

Let and var are operators that can be used to declare variables, but the difference between them is that var has scope promotion, and let is limited to the use of the current scope, otherwise an error will be reported. It will also be wrong to use before the statement.

console.log(a)
let a

Will say a is not defined

const is used to declare a constant. It cannot be changed after the declaration, and there is no problem of variable promotion. Using it before modification or declaration will report an error. We should also note that let and const declarations will not be hung on the window.

var a = 1
let b = 1
const c = 1
console.log(window.b) // undefined
console.log(window. c) // undefined

The interview question for the regular exam is, what does the following code output:

for (var i =0; i <5; i++) {
    setTimeout(()=>{
        console.log(i);
    },i*1000)
}
//5 5 5 5 5

This is the problem of block-level scope, and it will output 0 1 2 3 4 if it is replaced by let statement

in conclusion:

  • var has variable promotion and can be used before declaration. The other two have a temporary dead zone and cannot be used before the declaration
  • let and const are basically the same, the latter cannot be assigned again
  • Function promotion due to variable promotion
Arrow function

The arrow function is a new function writing method added by ES6. The following two writing methods are actually the same:

setTimeout(function(){
    console.log("Hello World!");
},1000)

setTimeout(()=>{
    console.log("Hello World!");
},1000)

What is the difference between it and ordinary functions?

  • Cannot be used as a constructor, no prototype
  • this points to inherited and will not change
Destructuring assignment

Destructuring assignment is a way of writing pattern matching. In the past, when we assign values, we usually have to assign them separately, such as:

let a = 1;
let b = 2;
let c = 3;

However, destructuring assignment allows us to assign values ​​in this way. Both the left and right sides correspond to copying. If the destructuring is unsuccessful, the value will be undefined

let [a, b, c] = [1, 2, 3];
let [a, b, c] = [1, 2];
console.log(a,b,c); //1, 2, undefined

There are generally two aspects that we commonly use. One is the deconstruction of JSON strings, such as:

const {name,age,number} = {name:'rose',age:12,number:123}
console.log(name,age,number);  //rose 12 123

There is also an exchange operation that we can use for data, such as:

let a=1;
let b=2;

[a,b]=[b,a];

console.log(a,b);  //2, 1
Template string
$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);
$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

Compared with the previous use + stitching is much simpler and more readable. The syntax is to use backticks to declare, and the variable uses $ {variable}.

Set, Map data structure

Set it is a constructor, used to generate Set data structure. Similar to an array, but unlike an array, it does not repeat each item. The effect can also be used for array deduplication operations.

const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
  console.log(i);
}
// 2 3 5 4

Array deduplication, relatively simple

function unique(arr) {
    return [...new Set(arr)]
}

Map is a collection of key-value pairs similar to objects, but the range of keys is not limited to strings, and various types of values ​​can be used as keys, including object.

const m = new Map();
const o = {p: 'Hello World'};

m.set(o, 'content')
m.get(o) // "content"

m.has(o) // true
m.delete(o) // true
m.has(o) // false

As a constructor, Map can also accept an array as a parameter, the members of the array are also an array of key-value pairs.

const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);

map.size // 2
map.has('name') // true
map.get('name') // "张三"
map.has('title') // true
map.get('title') // "Author"
Promise object
const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

The Promise constructor accepts a function as a parameter. The two parameters of the function are resolve and reject. They are two functions provided by the JavaScript engine and do not need to be deployed by yourself.

The function of the resolve function is to change the state of the Promise object from "uncompleted" to "successful" (that is, from pending to resolved), which is called when the asynchronous operation succeeds, and passes the result of the asynchronous operation as a parameter; reject The function of the function is to change the state of the Promise object from "uncompleted" to "failed" (that is, from pending to rejected), called when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.

After the Promise instance is generated, you can use the then method to specify the callback function of resolved state and rejected state respectively.

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});
Proxy

Proxy can be understood as setting up a layer of "interception" in front of the target object. Outside access to the object must first be intercepted by this layer, so it provides a mechanism to filter and rewrite the outside access. There are the following 13 types of Proxy interception. For specific usage, you can find the Proxy I wrote before.

  • get (target, propKey, receiver) intercepts object property reading
  • set (target, propKey, value, receiver) Intercept object property settings
  • has(target, propKey) 拦截propkey in proxy
  • deleteProperty(target, propKey) 拦截delete proxy[propKey]
  • ownKeys(target)
  • getOwnPropertyDescriptor (target, propKey) returns the object property description object interceptor
  • defineProperty(target, propKey, propDesc)
  • proventExtensions(target)
  • getPrototypeOf(target)
  • isExtensible(target)
  • setPrototypeOf(target, proto)
  • apply(target, object, args)
  • construct (target, args) intercepts proxy instances as operations called by the constructor

03 Summary


Many new features of ES6 can make ours simpler, but we need to understand every detail in it. Improper writing may cause our program to produce different operating results. If readers want to know more details, I recommend reading the third edition of Ruan Yifeng's ES6 entry standard, which will definitely gain a lot.
Insert picture description here

Published 57 original articles · won praise 6 · views 6419

Guess you like

Origin blog.csdn.net/weixin_42724176/article/details/104811046