ECMAScript 6 learning record (1)

Introduction

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

Count some new content first

  • let: Declare attribute keywords, block-level scope, no variable promotion, and temporary dead zone .
  • const: Declare a read-only constant. The pointing address is fixed and the content of the object can still be changed.
  • Template string: es6 string extension. The template string (template string) is an enhanced version of the string, identified by backticks (`). It can be used as an ordinary string, it can also be used to define a multi-line string, or embed variables in a string. It can also be used as a " label template " instead of the parentheses after the method.
  • includes(): returns a Boolean value, indicating whether the parameter string is found.
  • startsWith(): returns a Boolean value, indicating whether the parameter string is at the head of the original string.
  • endsWith(): returns a Boolean value, indicating whether the parameter string is at the end of the original string.
  • repeat(): returns a new string, which means repeating the original string n times.'hello'.repeat(2) // "hellohello"
  • padStart(): The function of string completion length. If a string is not enough for the specified length, it will be completed at the head or tail. padStart() is used for head completion.'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
  • padEnd(): The function of string completion length. If a string is not enough for the specified length, it will be completed at the head or tail. padEnd() is used for tail completion.'x'.padEnd(4, 'ab') // 'xaba'
  • trimStart(): Eliminate spaces at the head of the string.
  • trimEnd(): Eliminate trailing spaces.

Syntax of Module

What are ES6 modules

Chestnut: There is a calc method in A.js. B.js wants to use the calc method of A.js. In the past, they were introduced into html in an orderly manner. The module grammar can clearly indicate that the calc in A.js is a module method, and then B.js can be introduced to call the calc method.
The design idea of ​​ES6 modules is to be as static as possible, so that the dependencies of the modules and the input and output variables can be determined at compile time.
The module function mainly consists of two commands: export and import. The export command is used to specify the external interface of the module, and the import command is used to enter the functions provided by other modules.

// ES6 模块
import { stat, exists, readFile } from 'fs';

The essence of the above code is to load 3 methods from the fs module, other methods are not loaded. This kind of loading is called "compile-time loading" or static loading, that is, ES6 can complete module loading at compile time, and its efficiency is higher than that of CommonJS modules. Of course, this also makes it impossible to reference the ES6 module itself, because it is not an object.

export command

A module is an independent file. All variables inside the file cannot be obtained from outside. If you want the external to be able to read a variable inside the module, you must use the export keyword to export the variable. Below is a JS file that uses the export command to output variables.
Just lift chestnuts and finish:

// 声明时  export
export var firstName = 'Michael';
export function multiply(x, y) {
  return x * y;
};


// 声明后  export
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
function v1() { ... }
function v2() { ... }

export {
  firstName, lastName,year,v1,
  v2 as streamV2,
  v2 as streamLatestVersion
};

Syntactically speaking, there are only two ways to use modules:

  1. Export the module when declaring the field/method
  2. In the final unified export declaration module, braces must be required but the as alias is not necessarily used

Finally, there are two points to pay attention to in export :
1. The interface output by the export statement and its corresponding value are dynamically bound, that is, through this interface, you can get the real-time value inside the module.

export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);
//上面代码输出变量foo,值为bar,500 毫秒之后变成baz。

2. The export command can appear anywhere in the module, as long as it is at the top level of the module. If it is in the block-level scope, an error will be reported.
export official information

import command

After the external interface of the module is defined using the export command, other JS files can load the module through the import command.

// main.js
import { firstName, lastName, year } from './profile.js';

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}

The basic syntax is that import curly braces specify the imported module members, and then from the corresponding module file.
To summarize the import syntax:
1. Import members can also be aliased using as.
2. The path of from can be a relative path or an absolute path. You don’t need to write the .js suffix, or it can be a single module name, but you need to use configuration to tell javascript which file the hood module name specifies.
3. Multiple imports will only be executed once when importing the same member of the same module.
4. The attribute imported by the import command is readonly, and the imported object can modify the value and modify the real value of the original object (the official does not recommend this).
5. The import command is static, so no matter where it is in the file, it is executed first. Therefore, JavaScript expressions and variables cannot be used in inport.
import official information

Overall loading of modules

The import command described above is to specify to load a certain module member, and you can also directly load the entire module file.

// circle.js
export function area(radius) {
  return Math.PI * radius * radius;
}
export function circumference(radius) {
  return 2 * Math.PI * radius;
}

// 整体加载
// main.js
import * as circle from './circle';
console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));

The overall loading of the module official information

export default command

As can be seen from the previous example, when using the import command, the user needs to know the name of the variable or function to be loaded, otherwise it cannot be loaded.
For convenience and quick start, there is export default command. Specify the default output for the module.

// export-default.js
export default function () {
  console.log('foo');
}

When other modules load the module, the import command can specify any name for the anonymous function.

// import-default.js
import customName from './export-default';
customName(); // 'foo'

It should be noted that at this time, the braces are not used after the import command.
1. The export default command can export variables, methods or classes.
2. The essence of the export default command is to output a member with the name of default, so the declaration statement cannot be followed by default, but when other members use the alias as default, it is also pointed out anonymously, and default can be a specific value.
3. The default is the only module.

If you want to enter the default method and other interfaces in an import statement, you can write it as follows.

export default function (obj) {}
export function each(obj, iterator, context) {}
export { each as forEach };

import _, { each, forEach } from 'lodash';

export default output class

// MyClass.js
export default class { ... }

// main.js
import MyClass from 'MyClass';
let o = new MyClass();

export default command official information

Compound wording of export and import

When you need to introduce a module and then point it out, you can mix export and import to write

// 混合写法
export { foo, bar } from 'my_module';

// 可以简单理解为
import { foo, bar } from 'my_module';
export { foo, bar };

However, it should be noted that after writing in one line, foo and bar are not actually imported into the current module, but it is equivalent to forwarding these two interfaces to the outside, causing the current module to not directly use foo and bar.
Both the alias and the default point of the interface can be mixed with
export and import. Official information

import()

The import command is different from the import() function. The import command runs in the static compilation phase, and the import() function runs at runtime.
The import() function aims at dynamic loading.

import() official information

To be continued.
Copyright statement: The content of the article is summarized on the Internet. If it violates the rights of the original author, please contact me for deletion or authorization.

Guess you like

Origin blog.csdn.net/qq845484236/article/details/103871182