This article will give you an in-depth understanding of ES6 and learn about the new features of ES6. I hope it will be helpful to you!
Front-end (vue) entry to mastery course: enter learning
ECMAScript
is a脚本语言的标准化规范
developed by Netscape; originally namedMocha
, later renamedLiveScript
, and finally renamedJavaScript
ECMAScript 2015 (ES2015), version 6, originally known as ECMAScript 6 (ES6
), adds new features.
ES6 block scope let
First, what is scope? Scope simply means declaring a variable. The valid scope of this variable is before let
comes. js only has全局作用域
and函数作用域
of var
, and ES6
brings块级作用域
to js.
{ var a = "?"; let b = "⛳"; } console.log(a); console.log(b);
? Uncaught ReferenceError: b is not defined
As you can see, we use the var keyword to define variable a in the block. In fact, it can be accessed globally. Therefore, var声明的变量是全局的
, but we want the variable to take effect in the block and be accessed after leaving the block. No, then you can use the new block-level scope keyword let
in ES6
to declare the variable a. When I access it again, an error is reported, saying a is not defined
, a is not defined.
As shown below, first define a function that returns an array. Before using the destructured array, call the array and assign the return value to temp, and then print the temp array. After using解构数组
, directly define an array variable, and then The function return value points to the variable. It will automatically assign the value of the first item to the first array variable, the second item to the second array variable, and so on. Finally, the three variables are printed and there is no problem.
function breakfast() { return ['?', '?', '?']; } var temp = breakfast(); console.log(temp[0], temp[1], temp[2]); let [a, b, c] = breakfast(); console.log(a, b, c);
? ? ? ? ? ?
First, the breakfast
function returns an对象
. Use解构对象
to define the object. The key in the key-value pair represents the key name of the actual object mapped. The value is the custom variable. After destructuring is completed, the assignment will be completed automatically. Then the breakfast function is called to return the object. Then print the variables a, b, c and you can see that there is no problem
function breakfast() { return { a: '?', b: '?', c: '?' } } let { a: a, b: b, c: c } = breakfast(); console.log(a, b, c);
? ? ?
Before using the template string, we concatenate the string variables using +
Use the template string provided by ES6. First use `` to wrap the string. When you want to use variables, use ${变量}
let a = '?', b = '?️'; let c = 'Eat today' + a + 'See after eating' + b; console.log(c); let d = `Eat ${a} today and watch after eating ${b}`; console.log(d);
Eat today? Let’s see after eating?️ Eat today? Let’s see after eating?️
Using these functions, you can easily complete operations such as whether the string starts with something, whether the string ends with something, and whether it contains any string.
let str = 'Hello, I am Xiao Zhou ❤️'; console.log(str.startsWith('Hello')); console.log(str.endsWith('❤️')); console.log(str.endsWith('Hello')); console.log(str.includes(" "));
true true false true
In ES6, you can use default parameters. When calling a function, if no value is assigned to the parameter, it will be executed using the set default parameters. When a value is assigned to the parameter, it will be executed using the newly assigned value, overwriting the default value. Use the following:
function say(str) { console.log(str); } function say1(str = 'Hey') { console.log(str); } say(); say1(); say1('❤️');
undefined Hey hey❤️
Use ...
to expand elements for easy operation. Use as follows:
let arr = ['❤️', '?', '?']; console.log(arr); console.log(...arr); let brr = ['Prince', ...arr]; console.log(brr); console.log(...brr);
[ '❤️', '?', '?' ] ❤️ ? ? [ 'Prince', '❤️', '?', '?' ] Prince ❤️ ? ?
The ...
operator is used on function parameters and receives an array of parameters. It is used as follows:
function f1(a, b, ...c) { console.log(a, b, c); console.log(a, b, ...c); } f1('?','?','☃️','㊙️');
? ? [ '☃️', '㊙️' ] ? ? ☃️ ㊙️
You can use .name
to get the name of the function. The specific usage is as follows:
function f1() { } console.log(f1.name); let f2 = function () { }; console.log(f2.name); let f3 = function f4() { }; console.log(f3.name);
f1 f2 f4
Using arrow functions can make the code more concise, but you must also pay attention to the limitations of arrow functions, and the arrow function itself does not have this, this points to the parent
let f1 = a => a; let f2 = (a, b) => { return a + b; } console.log(f1(10)); console.log(f2(10, 10));
10 20
Using the object expression of es6, if the object attribute is the same as the value, the value can be omitted, and function
can be omitted when writing the function. The usage is as follows:
let a = '㊙️'; let b = '☃️'; const obj = { a: a, b: b, say: function () { } } const es6obj = { a, b, say() { } } console.log(obj); console.log(es6obj);
{ a: '㊙️', b: '☃️', say: [Function: say] } { a: '㊙️', b: '☃️', say: [Function: say] }
Use the const
keyword to define measurement. const
limits the action of assigning values to the measurement, but does not limit the value in the measurement. Use the following:
const app = ['☃️', '?']; console.log(...app); app.push('?'); console.log(...app); app = 10;
You can see that when assigning a value to the measurement again, an error is reported.
☃️ ? ☃️ ? ? app = 10; ^ TypeError: Assignment to constant variable.
When using dots to define object attributes, if the attribute name contains space characters, it is illegal and the syntax cannot be passed. Using [属性名]
can perfectly solve the problem, and not only can the attribute name be written directly, but also can be specified using variables. The specific usage is as follows:
let obj = {}; let a = 'little name'; obj.name = 'Prince'; // It is illegal to use dots to define attributes with spaces in the middle // obj.little name = 'Little Prince'; obj[a] = 'Little Prince'; console.log(obj);
{ name: 'Prince', 'little name': 'Little Prince' }
The results of comparing some special values using ===
or ==
may not meet your needs. You can use Object.is(第一个值,第二个值)
to judge, and you may be happy. laughed
console.log(NaN == NaN); console.log(+0 == -0); console.log(Object.is(NaN, NaN)); console.log(Object.is(+0, -0));
false true true false
Use Object.assign()
to copy one object to another object, as follows:
let obj = {}; Object.assign( // source obj, //Copy target object { a: '☃️' } ); console.log(obj);
{ a: '☃️' }
You can use es6 to set the prototype of an object as follows:
let obj1 = { get() { return 1; } } let obj2 = { a: 10, get() { return 2; } } let test = Object.create(obj1); console.log(test.get()); console.log(Object.getPrototypeOf(test) === obj1); Object.setPrototypeOf(test, obj2); console.log(test.get()); console.log(Object.getPrototypeOf(test) === obj2);
1 true 2 true
let obj1 = { get() { return 1; } } let obj2 = { a: 10, get() { return 2; } } let test = { __proto__:obj1 } console.log(test.get()); console.log(Object.getPrototypeOf(test) === obj1); test.__proto__ = obj2; console.log(test.get()); console.log(Object.getPrototypeOf(test) === obj2);
1 true 2 true
let obj1 = { get() { return 1; } } let test = { __proto__: obj1, get() { return super.get() + ' ☃️'; } } console.log(test.get());
1 ☃️
Before learning, first write an iterator
function die(arr) { let i = 0; return { next() { let done = (i >= arr.length); let value = !done ? arr[i++] : undefined; return { value: value, done: done } } } } let arr = ['☃️', '?', '?']; let dieArr = die(arr); console.log(dieArr.next()); console.log(dieArr.next()); console.log(dieArr.next()); console.log(dieArr.next());
{ value: '☃️', done: false } { value: '?', done: false } { value: '?', done: false } { value: undefined, done: true }
OK, let’s look at the simplified generator
function* die(arr) { for (let i = 0; i < arr.length; i++) { yield arr[i]; } } let test = die(['?','☃️']); console.log(test.next()); console.log(test.next()); console.log(test.next());
{ value: '?', done: false } { value: '☃️', done: false } { value: undefined, done: true }
Use es6 to build classes quickly and conveniently, great
class stu { constructor(name) { this.name = name; } say() { return this.name + 'Say Ori'; } } let xiaoming = new stu("小明"); console.log(xiaoming.say());
Xiao Ming said Ori gave
Define get/set methods to obtain or modify class attributes
class stu { constructor(name) { this.name = name; } get() { return this.name; } set(newStr) { this.name = newStr; } } let xiaoming = new stu("小明"); console.log(xiaoming.get()); xiaoming.set("Daming") console.log(xiaoming.get());
Xiao Ming and Da Ming
Methods modified with the static keyword can be used directly without instantiating the object.
class stu { static say(str) { console.log(str); } } stu.say("Original static method");
Origi static method
Using inheritance can reduce code redundancy, such as:
class Person { constructor(name, bir) { this.name = name; this.bir = bir; } showInfo() { return 'Name:' + this.name + 'Birthday:' + this.bir; } } class A extends Person { constructor(name, bir) { super(name, bir); } } let zhouql = new A("Zhou Qiluo", "2002-06-01"); // Zhou Qiluo itself does not have a showInfo method, it is inherited from Person's console.log(zhouql.showInfo());
Name: Zhou Qiluo Birthday: 2002-06-01
Set collection, unlike arrays, does not allow duplicate elements in Set collection
//Create a Set collection let food = new Set('??'); // Add repeatedly, only one can go in food.add('?'); food.add('?'); console.log(food); //Current collection size console.log(food.size); // Determine whether an element exists in the collection console.log(food.has('?')); // Delete an element in the collection food.delete('?'); console.log(food); // Loop through the collection food.forEach(f => { console.log(f); }); // Clear the collection food.clear(); console.log(food);
Set(3) { '?', '?', '?' } 3 true Set(2) { '?', '?' } ? ? Set(0) {}
Map combines to store key-value pairs
let food = new Map(); let a = {}, b = function () { }, c = "name"; food.set(a, '?'); food.set(b, '?'); food.set(b, '?'); food.set(c, 'rice'); console.log(food); console.log(food.size); console.log(food.get(a)); food.delete(c); console.log(food); console.log(food.has(a)); food.forEach((v, k) => { console.log(`${k} + ${v}`); }); food.clear(); console.log(food);
Map(3) { {} => '?', [Function: b] => '?', 'name' => 'rice' } 3 ? Map(2) { {} => '?', [Function: b] => '?' } true [object Object] + ? function () { } + ? Map(0) {}
Using modular development, es6 can easily import and export some content, as well as default export and other details.
let a = '?'; let f1 = function (str = 'Your parameters') { console.log(str); } export { a, f1 };
import {a, f1} from './27moduletest.js'; console.log(a); f1(); f1('got it');