ES6 usage subtotal

One, let

ES6 has added letcommands to declare variables. Its usage is similar var, but the declared variable is only valid in letthe code block where the command is located.

Why do you need block-level scope?

ES5 has only global scope and function scope, not block-level scope, which brings many unreasonable scenarios.

In the first scenario, inner variables may override outer variables.

var tmp = new Date();

function f() {
  console.log(tmp);
  if (false) {
    var tmp = 'hello world';
  }
}

f(); // undefined

The original intention of the above code is that ifthe outside of the code block uses the outer tmpvariables, and the inner uses the inner tmpvariables. However, fafter the function is executed, the output result is undefinedthat the variable is promoted, which causes the inner tmpvariable to cover the outer tmpvariable.

In the second scenario, the loop variable used for counting is leaked as a global variable.

var s = 'hello';

for (var i = 0; i < s.length; i++) {
  console.log(s[i]);
}

console.log(i); // 5

In the above code, the variable is ionly used to control the loop, but after the loop is over, it does not disappear and leaks into a global variable.

ES6's block-level scope

letIn fact, block-level scope is added to JavaScript.

function f1() {
  let n = 5;
  if (true) {
    let n = 10;
  }
  console.log(n); // 5
}

The above function has two code blocks, both of which declare variables n, and output 5 after running. This means that the outer code block is not affected by the inner code block. If you use the vardefined variable twice n, the final output value is 10.

 

2. Deconstruction and assignment of variables

ES6 allows extracting values ​​from arrays and objects and assigning values ​​to variables according to a certain pattern, which is called Destructuring.

Previously, when assigning a value to a variable, you could only specify the value directly.

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

ES6 allows it to be written as follows.

let [a, b, c] = [1, 2, 3];

The above code indicates that you can extract values ​​from the array and assign values ​​to variables according to the corresponding positions.

Essentially, this type of writing belongs to "pattern matching", as long as the patterns on both sides of the equal sign are the same, the variable on the left will be assigned the corresponding value. Here are some examples of destructuring using nested arrays.

Object destructuring assignment

Introduction

Destructuring can be used not only for arrays, but also for objects.

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

There is an important difference between object destructuring and arrays. The elements of the array are arranged in order, and the value of the variable is determined by its position; and the properties of the object have no order, and the variable must have the same name as the property in order to get the correct value.

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

In the first example of the above code, the order of the two variables on the left side of the equal sign is inconsistent with the order of the two attributes with the same name on the right side of the equal sign, but it has no effect on the value. The variable in the second example does not have a corresponding attribute with the same name, resulting in not getting a value, and finally being equal undefined.

If the destructuring fails, the value of the variable is equal to undefined.

let {foo} = {bar: 'baz'};
foo // undefined

In the above code, the object on the right side of the equal sign has no fooattributes, so the variable can foonot take a value, so it is equal undefined.

 

Three, Symbol

ES6 introduces a new primitive data type Symbolthat represents a unique value. It is the seventh data types JavaScript language, the first six are: undefined, , nullBoolean (Boolean), string (String), value (Number), objects (Object).

Four, set, map

set: ES6 provides a new data structure Set. It is similar to an array, but the values ​​of the members are unique , there is no duplicate value, add values ​​to the object through add

let set = new Set([1, 2, 3, 4, 4]);
set.add(5)

map:

JavaScript object (Object) is essentially a collection of key-value pairs (Hash structure), but traditionally only strings can be used as keys

ES6 provides Map data structure. It is similar to an object and is also a collection of key-value pairs, but the scope of "keys" is not limited to strings. Various types of values ​​(including objects) can be used as keys. In other words, the Object structure provides a "string-value" correspondence, and the Map structure provides a "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value pair" data structure, Map is more suitable than 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

The above code uses the Map structure setmethod to treat the object oas ma key, then uses the getmethod to read the key, and then uses the deletemethod to delete the key.

Five, Proxy

Proxy can be understood as setting up a layer of "interception" in front of the target object. Any external access to the object must first pass through this layer. Therefore, it provides a mechanism to filter and rewrite external access. The original meaning of the word Proxy is proxy. It is used here to mean "proxy" certain operations, which can be translated as "proxy".

var obj = new Proxy({}, {
  get: function (target, propKey, receiver) {
    console.log(`getting ${propKey}!`);
    return Reflect.get(target, propKey, receiver);
  },
  set: function (target, propKey, value, receiver) {
    console.log(`setting ${propKey}!`);
    return Reflect.set(target, propKey, value, receiver);
  }
});

The above code getsets up a layer of interception for an empty object, and redefines the behavior of reading ( ) and setting ( set) properties . The specific grammar will not be explained here for the time being, just look at the running results. objTo read and write the properties of the object with interception behavior set , you will get the following result.

obj.count = 1
//  setting count!
++obj.count
//  getting count!
//  setting count!
//  2

The above code shows that Proxy actually overloads the dot operator, that is, it overwrites the original definition of the language with its own definition.

Guess you like

Origin blog.csdn.net/Mr_linjw/article/details/113932705