ES6 study notes

1,ES6

1.1. What is ES6

The programming language JavaScript is the implementation and extension of ECMAScript. ECMAScript is a syntax specification standardized by ECMA (a standards organization similar to W3C). ECMAScript defines:

Language grammar – syntax parsing rules, keywords, statements, declarations, operators, etc.

type – Boolean, number, string, object, etc.

Prototype and inheritance

Of built-in objects and functions Standard libraryJSON,Math,Array method,Object introspection method Wait.

ECMAScript standard does not define functions related to HTML or CSS, nor does it define functions similar to DOM (document object model) Web API , these are defined in separate standards. ECMAScript covers the usage scenarios of JS in various environments, whether browser environment or similar node.js Non browser environment.

The historical versions of ECMAScript standard are 1, 2, 3 and 5 respectively.

So why not version 4? In fact, in the past, it was planned to release version 4, which proposed a large number of new features, but it was finally abolished because the idea was too radical (this version of the standard once had an extremely complex built-in static type system supporting generics and type inference).

ES4 was controversial. When the standards committee finally stopped developing ES4, its members agreed to release a relatively modest version of ES5, and then continue to develop some more substantive new features. This explicit negotiation agreement is finally named "Harmony". Therefore, the ES5 specification contains such two sentences

ECMAScript is a dynamic language that is constantly evolving.

Important technical improvements will continue in future versions of the specification

The improved version ES5 released in 2009 introduces Object.create(),Object.defineProperty(),getters and setters,Strict mode as well as JSON Object.

ECMAScript 6.0 (hereinafter referred to as ES6) is the next generation standard of JavaScript language, which was officially released in June 2015. Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language.

1.2 new features of grammar

1.2.1. New variable declaration

  1. We all know that before ES6, var keyword declared variables. Wherever it is declared, it is considered to be declared at the top of the function (not within the function, that is, at the top of the global scope). This is the function variable promotion, for example:
function aa() {
    if(bool) {
        var test = 'hello man'
        } else {
            console.log(test)
        }
}
  • The above code is actually:
function aa() {
    var test // Variable promotion
    if(bool) {
        test = 'hello man'
    } else {
        //The test value accessed here is undefined
        console.log(test)
    }
    //The test value accessed here is undefined
}
  • So don't worry about whether bool is true or false. In fact, test will be declared anyway.
  1. We usually use let and const to declare. Let represents variable and const represents constant. Let and const are both block level scopes. How to understand this block level scope? Inside a function, inside a code block. Look at the following code
function aa() {
    if(bool) {
        let test = 'hello man'
        } else {
            //test cannot be accessed here
            console.log(test)
        }
}
  1. const is used to declare constants. See the following code
const name = 'lux'
name = 'joe' 	//If the value is assigned again, an error will be reported

Assignment to constant variable: assignment to constant variable

1.2.2 template string

  1. es6 template characters are a blessing for developers. They solve the pain points of ES5 in string function.

    The first purpose is basic string formatting. Embed expressions into strings for splicing. Defined by ${}.

//es5 
var name = 'lux'
console.log('hello' + name)
//es6
const name = 'lux'
console.log(`hello ${name}`) //hello lux
  1. Second, in ES5, we use backslashes (\) to do multi line string or string line by line splicing. ES6 reverse quotation mark (` `) is directly handled.
// es5
var msg = "Hi \
man!"
// es6
const template = `<div>
<span>hello world</span>
</div>`

1.2.3 function default parameters

  1. ES6 provides default values for parameters. This parameter is initialized when the function is defined so that it can be used when the parameter is not passed in.
  2. Look at the example code
function action(num = 200) {
    console.log(num)
}
action() //200
action(300) //300

1.2.4 arrow function

The interesting part of ES6 is the quick writing of functions. That is, the arrow function.

The three most intuitive features of arrow function.

  • The function keyword is not required to create a function
  • Omit the return keyword
  • Inherit the this keyword of the current context

1. Basic function

function funcName(params) {
    return params + 2;
}
funcName(2);

2. Use arrow function

var funcName = (params) => params + 2
funcName(2)

3. Basic syntax of arrow function

(parameters) => { statements }
  • If there are no parameters, it can be further simplified:
() => { statements }
  • If there is only one parameter, parentheses can be omitted:
parameters => { statements }
  • If the return value has only one expression, you can also omit braces:
parameters => expression
 
// Equivalent to:
function (parameters){
  return expression;
}

For example:

var double = num => num * 2
double(2);
double(3);

4. There is no local binding of this. Unlike ordinary functions, arrow functions do not bind this. Or the arrow function will not change the original binding of this.

4.1. We use an example to illustrate:

function Count() {
  this.num = 0;
}
var a = new Count();

4.2. Because the keyword new is used to construct, this in the Count() function is bound to a new object and assigned to a. Via console Log print a.num and 0 will be output.

console.log(a.num);

4.3 let's take a look at the output results: if we want to add 1 to the value of a.num every second, how can we achieve it? You can use the setInterval() function.

function Count() {
  this.num = 0;
  this.timer = setInterval(function add() {
    this.num++;
    console.log(this.num);
  }, 1000);
}
var b = new Count();

4.4. You will find that there will be a NaN printed out every second instead of an accumulated number. What's wrong? In fact, this in setInterval is bound to the global object. We can verify this by printing this:

function Count() {
    this.num = 100;
    setTimeout(function add(){
        this.num++;
        console.log(this);
    },1000)
}
var a = new Count();
console.log(a.num)
  • Back to the previous function, NaN is printed because of this Num is bound to the num of the window object, and window Num is undefined.

4.5. So how can we solve this problem? Use the arrow function! Using the arrow function will not cause this to be bound to the global object.

function Count(){
    this.num = 100;
    setInterval(()=>{
        this.num++
        console.log(this.num);
    },1000)
}
var a = new Count();
console.log(a.num)
  • This bound through the Count constructor will be preserved. In the setInterval function, this still points to the newly created b object.

4.6. To verify the statement just made, we can bind this in the Count function to that, and then judge whether this and that are the same in setInterval.

function Counter() {
  var that = this;
  this.timer = setInterval(() => {
    console.log(this === that);
  }, 1000);
}
var b = new Counter();
  • Summary as we expected, the printed value is true every time. Finally, end the screen printing:

5. The arrow function has a more concise syntax for writing code; this will not be bound.

1.2.5 object initialization abbreviation

  1. ES5 we write objects in the form of key value pairs, which may have duplicate names. for example
function people(name, age) {
    return {
        name: name,
        age: age
    };
}
  1. The above code can be abbreviated as
function people(name, age) {
    return {
        name,
        age
    };
}

1.2.6 deconstruction

  1. Arrays and objects are the most commonly used and important representations in JS. In order to simplify the extraction of information, ES6 adds deconstruction, which is the process of decomposing a data structure into smaller parts
  2. ES5 we extract the information in the object in the following form
const people = {
    name: 'lux',
    age: 20
}
const name = people.name
const age = people.age
console.log(name + ' --- ' + age)
  1. Do you feel familiar? Yes, that's how we got object information before ES6, one by one. Now, the deconstruction of ES6 allows us to take data from objects or arrays and save it as variables, such as
//object
const people = {
    name: 'lux',
    age: 20
}
const { name, age } = people
console.log(`${name} --- ${age}`)
//array
const color = ['red', 'blue']
const [first, second] = color
console.log(first) //'red'
console.log(second) //'blue'

1.2.7,Spread Operator

Another interesting feature in ES6 is the Spread Operator, which also has three points... Next, let's show its purpose. Assemble objects or arrays

//array
const color = ['red', 'yellow']
const colorful = [...color, 'green', 'pink']
console.log(colorful) //[red, yellow, green, pink]

//object
const alp = { fist: 'a', second: 'b'}
const alphabets = { ...alp, third: 'c' }
console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"

1.2.8 import and export

  1. Import import module, export export module
  2. Create the file lib js
let fn0=function(){
    console.log('fn0...');
}
export {fn0}
  1. Create file demo9 js
import {fn0} from './lib'
fn0();
  1. Note: node(v8.x) itself does not support the import keyword, so we need to use babel's command-line tool to execute it
babel-node demo9
  1. Use export default to export an object

    Exports.obj={}

export default {
    a:20,
    say(){
        console.log(this.a);
    } 
};
  1. The imported name can be customized

    Let obj = require("./vue");

import v from './vue'
v.say();

1.2.9,Array.some()

  1. The some () method tests whether an element in the array passes the test implemented by the provided function.
  2. grammar
array.some(callback[, thisObject]);
  • callback - a function that tests each element.

  • thisObject - the object used as this object when the callback is executed.

  • If an element passes the test, it returns true; otherwise, it returns false.

  1. case
function isBigEnough(element, index, array) {
    return (element >= 10);
}
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval );

var retval = [12, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval );

1.2.10,Array.includes()

  1. Array.includes() determines whether an element is included. It directly returns true or false to indicate whether an element is included. It is equally valid for NaN
  2. grammar
str.includes(searchString[, position])
  • searchString - the substring to search.

  • Position - the position in this string where the searchString search starts; The default is 0.

  • true if the string contains substrings; Otherwise, false.

  1. case
let arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN]
arr1.includes('c')    // true
arr1.includes('z')    // false
arr1.includes(NaN)    // true
//The second parameter of the include () function indicates the starting position of the judgment
arr1.includes('d', 1)    // true
arr1.includes('d', 3)    // true
arr1.includes('d', 4)    // false
//The second parameter can also be a negative number, which indicates the number from the right, but does not change the search direction. The search direction is still from left to right
arr1.includes('k', -1)    // false
arr1.includes('k', -2)    // true
arr1.includes('i', -3)    // false

Keywords: Javascript Front-end ECMAScript

Added by [PQ3]RogeR on Tue, 01 Feb 2022 13:20:52 +0200