Powered by md-Blog  文 - 篇  访客 -

ES6(ES2015)语法入门示例


  分类:大前端  / 
更新:2020-11-01 17:25:19  /  创建:2020-01-23 13:24:26
不要删除

0、请使用严格模式

Demo.js
'use strict'

ES6可以理解为ES5的语法糖集合,您可通过以下网址进行ES6语法转换:

https://www.babeljs.cn/repl

默认使用 const,多次绑定用 let,尽可能少的去使用 var。

1、块作用域 let

var

if(true){
    var phone = 'iPhone11';
}
console.log(phone); // iPhone11

let

if(true){
    let phone = 'iPhone11';
    console.log(phone); // iPhone11
}
console.log(phone); // phone is not defined

2、恒量 const

const phone = 'iPhone11';
console.log(phone); // iPhone11
const phone = 'iPhone12';
console.log(phone); // SyntaxError
const person = {    // 此处对象的值可以改变
    name: 'Sam',
    age: 20
}
const Sam = Object.freeze(person);  // 此时对象的值将无法修改
const arr = [];
arr.push('iPad')
console.log(arr)    // ["iPad"]
arr.push('iPhone')
console.log(arr)    // ["iPad", "iPhone"]
const arr = [];
console.log(arr)    // SyntaxError

3、解构数组

const numbers = ['one', 'two', 'three'];

const [a, b] = numbers;
console.log(a, b); // one two

const [aa, ,cc] = numbers;
console.log(aa, cc);  // one three

// ... 用法,后面会讲到
const [aaa, ...others] = numbers;
console.log(aaa, others);   // one (2) ["two", "three"]

方便的值转换

let a = 10;
let b = 20;

[a, b] = [b, a];
console.log(a, b);  // 20 10

4、解构对象

const User = {
    name: 'admin',
    pwd: '123',
    keys: {
        key1: '34324',
        key2: 'abcde'
    }
}

const { name, pwd } = User;
console.log(name);  // admin
console.log(pwd);   // 123

const { key1, key2 } = User.keys;
console.log(key1);  // 34324
console.log(key2);  // abcde

// 赋新变量
const { key1: k1, key2: k2 ,date = '2020-02-18' } = User.keys;
console.log(k1);    // 34324
console.log(k2);    // abcde
console.log(date);  // 2020-02-18

无对象属性值提供默认值,常见于插件默认值概念。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>
<body>
    
</body>
</html>

<script>
'use strict'

function newDiv(option= {}){
    const { width = '100px', height = '50px', bgc = '#F60' } = option;
    const div = document.createElement('div');
    div.style.width = width;
    div.style.height = height;
    div.style.background = bgc;
    document.querySelector('body').appendChild(div);
}

newDiv({
    width: '200px',
    height: '200px'
})
</script>

5、模板字符串

const phone = 'iPhone11',
    pad = 'iPad Pro';

// 之前
const my_edc_1 = '我的背包中有 ' + phone + ' 与 ' + pad + '。';
console.log(my_edc_1);    // 我的背包中有 iPhone11 与 iPad Pro。

// 模板字符串
const my_edc_2 = `我的背包中
    有 ${ phone } 与 ${ pad } 。`;

console.log(my_edc_2);    //      我的背包中
                          // 有 iPhone11 与 iPad Pro 。

6、带标签的模板字符串

const phone = 'iPhone11',
      pad = 'iPad Pro';

// 模板字符串
const my_edc = bags`我的背包中有 ${ phone } 与 ${ pad } 。`;

function bags(strings, ...values){
    console.log(strings);   // [ '我的背包中有 ', ' 与 ', ' 。' ]
    console.log(values);    // [ 'iPhone11', 'iPad Pro' ]
}

7、判断字符串是否包含其他字符串

  • startsWith 是否以 x 开头,大小写敏感。
  • endsWith 是否以 x 结尾,大小写敏感。
  • includes 是否包含 x,大小写敏感。
  • repeat 重复。
const phone = 'iPhone11',
    pad = 'iPad Pro';

// 模板字符串
const my_edc = `我的背包中有 ${ phone } 与 ${ pad } 。`;
console.log(
    my_edc.startsWith('我的背包'),   // true
    my_edc.endsWith('。'),   // true
    my_edc.includes('i')   // true
);
const id = '0123452020123456';
console.log(id.startsWith('2020', 6));    // id 第7位是否以 2020 开头,true
const string = 'I love you';
console.log(string.endsWith('love', 6));    // 从左往右第6位是否以 love 结尾, true
const string = '哈';
console.log(string.repeat(7));    // 哈哈哈哈哈哈哈

8、默认参数

const add = (a = 5, b = 2)=>{
    console.log(a + b);
}

add(20, 10);    // 30
add();  // 7
add(9);     // 11
add(undefined, 8);   // 13

9、...

扩展数组

const arr1 = ['1', '2', '3'];
const arr2 = ['5', '6', '7'];

let arr = [...arr1, '4', ...arr2];
console.log(arr);   // ["1", "2", "3", "4", "5", "6", "7"]

注意:如果需要赋值给新的数组:

const arr1 = ['1', '2', '3'];
const arr2 = [...arr1];   // 这样写
const arr3 = arr1;    // 千万别这样写,这样会导致修改 arr3 会连 arr1 一起修改。

剩余参数

let my_edc = ['iPhone11', 'iPad Pro'];
let your_edc = ['oppo Reno', ...my_edc];

console.log(...my_edc)  //展开数组:iPhone11 iPad Pro
console.log(...your_edc)  //展开数组再组合:oppo Reno iPhone11 iPad Pro

其他多余的都存在 others 的数组里:

function my_edc(phone, pad, ...others){
    console.log(phone, pad, others)
}

my_edc('iPhone11', 'iPad Pro', 'xbox', 'kindle');   // iPhone11 iPad Pro [ 'xbox', 'kindle' ]

存在 others 数组里再展开:

function my_edc(phone, pad, ...others){
    console.log(phone, pad, ...others)
}

my_edc('iPhone11', 'iPad Pro', 'xbox', 'kindle');   // iPhone11 iPad Pro xbox kindle

一个求和例子:

function sum (...items){
    return items.reduce((prev, curr) => prev + curr, 0)
}

console.log(sum(3, 4))    // 7
console.log(sum(3, 4, 8, 1))    // 16

10、name 属性

输出变量、函数的名字
let now_edc = function my_edc(){
}

console.log(now_edc.name)   // my_edc

11、for...of 循环

  • for...of 循环替代 for...in 和 forEach()。
  • 支持 break、continue。
  • 还不支持对象。
const arr = ['a', 'b', 'c', 'd'];

for(let item of arr){
    console.log(item);
}

// a
// b
// c
// d

entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。

const arr = ['a', 'b', 'c', 'd'];

for(let item of arr.entries()){
    console.log(item);  // 获取数组
    console.log(item[0]);   // 获取索引
    console.log(item[1]);   // 获取值
}

常这样写:

const arr = ['a', 'b', 'c', 'd'];

for(let [index, item] of arr.entries()){
    console.log(index);  // 获取索引
    console.log(item);   // 获取值
}

12、箭头函数

// 箭头函数为匿名函数
let res = (a, b) => a * b;  
// 隐式返回,可以省略 return,和 { }

console.log(res(2, 5));     // 10

等同于

var res = function res(a, b) {
  return a * b;
};

console.log(res(2, 5));     // 10

Tips:

  • 箭头函数 this 继承父作用域,不用再 var _this = this 或者 var self = this 来变通了。
  • 在建构函数、包括对象的函数中,不可使用箭头函数。原因还是 this
  • 如果使用 arguments 对象,不可使用箭头函数。

13、对象表达式

let a = 1, b = 2;
let obj = {
    a,
    b
}
console.log(obj);   // { a: 1, b: 2 }

等同于

var a = 1,
    b = 2;
var obj = {
  a: a,
  b: b
};

14、对象属性名

let obj = {};
let tools = 'pc';

obj.phone = 'iPhone11';
obj['pad'] = 'iPad';
obj[tools] = 'iMac'
console.log(obj);    // { phone: 'iPhone11', pad: 'iPad', pc: 'iMac' }

15、把对象的值赋到另一个对象里

let obj = {};
Object.assign(
    obj,
    {'phone': 'iPhone 11'}
)
console.log(obj);   // { phone: 'iPhone 11' }

16、setPrototypeOf

将一个指定的对象的原型设置为另一个对象或者null
let color_1 = {
    get_color() {
        return 'red';
    }
}

let color_2 = {
    get_color() {
        return 'blue';
    }
}

let color = Object.create(color_1);
console.log(color.get_color()); // red
console.log(Object.getPrototypeOf(color) === color_1);  // true

Object.setPrototypeOf(color, color_2);
console.log(color.get_color());  // blue
console.log(Object.getPrototypeOf(color) === color_1);  // false
console.log(Object.getPrototypeOf(color) === color_2);  // true

17、 __proto__

let c_1 = {
    get_color(){
        return 'red';
    }
}
let c_2 = {
    get_color(){
        return 'blue';
    }
}

// 在对象表达式中设置
let my_phone = {
    __proto__:  c_1
}

console.log(my_phone.get_color());  // red
console.log(Object.getPrototypeOf(my_phone) === c_1); // true

// 设置对象的 __proto__
my_phone.__proto__ = c_2;
console.log(my_phone.get_color());  // blue
console.log(Object.getPrototypeOf(my_phone) === c_2); // true

原型 prototype__proto__ 存在的意义是什么?

__proto__ 用来读取或设置当前对象的 prototype 对象

prototype 指向一块内存,这个内存里面有共用属性

__proto__ 指向同一块内存

prototype__proto__ 的不同点在于

prototype 是构造函数的属性,而 __proto__ 是对象的属性

难点在于……构造函数也是对象!

反证法

假设我们把 __proto__ 去掉,那么

var obj = {}
obj.toString() // 报错,没有 toString 方法

所以你只能这样声明一个对象咯:

var obj = {
  toString: window.Object.prototype.toString,
  valueOf: window.Object.ptototype.valueOf
}
obj.toString() // '[object Object]'

知道 __proto__ 帮你省多少代码了吗?

如果没有 prototype,那么共用属性就没有立足之地

如果没有 __proto__,那么一个对象就不知道自己的共用属性有哪些。

假设我们删掉 prototype,包括 window.Object.prototypewindow.Array.prototype

那么 window.Object.prototype.toString 也一并被删除了。

然后我们基本就没法写代码了……

var obj = {}
obj.toString() // toString 不存在,因为 toString 没有定义过啊

prototype 的意义就是把共有属性预先定义好,给之后的对象用。

18、super

let c_1 = {
    get_color(){
        return 'red';
    }
}
let c_2 = {
    get_color(){
        return 'blue';
    }
}

// 在对象表达式中设置
let my_phone = {
    __proto__:  c_1,
    get_color() {
        return super.get_color() + 'pink';
    }
}

console.log(my_phone.get_color());  // redpink

19、Symbol

表示独一无二的值,最大的用法是用来定义对象的唯一属性名

ES6 数据类型除了 Number 、 String 、 Boolean 、 Objec t、 null 和 undefined ,还新增了 Symbol 。

let sy = Symbol("KK");
console.log(sy);   // Symbol(KK)
console.log(typeof(sy));        // symbol
 
// 相同参数 Symbol() 返回的值不相等
let sy1 = Symbol("kk"); 
console.log(sy === sy1);       // false

20、迭代器 Iterators

迭代器一次返回一个值和一个done
const items = ["zero", "one", "two"];
const it = items[Symbol.iterator]();
 
console.log(it.next());  // { value: "zero", done: false }
console.log(it.next());  // { value: "one", done: false }
console.log(it.next());  // { value: "two", done: false }
console.log(it.next());  // { value: undefined, done: true }

21、生成器 Generators

自动生成迭代器
function* colors() {
    yield 'red';
    yield 'blue';
}

let my_color = colors();

// 等同于

let colors = function* (items) {
    for (var i = 0; i < items.length; i++) {
        yield items[i];
    }
}

let my_color = colors(['red', 'blue']);

// 得出结果

console.log(my_color.next());   // { value: 'red', done: false }
console.log(my_color.next());   // { value: 'blue', done: false }
console.log(my_color.next());   // { value: 'undefined', done: true }

22、类 class、get、set

class Point {
    constructor(x, y) {
      this.x = x;
      this.y = y;
      this.colors = [];
    }

    get color() {
        return this.colors;
    }

    set color(color) {
        this.colors.push(color);
    }
  
    xy() {
      return this.x * this.y;
    }
}

let my_pt = new Point(3, 7);
console.log(my_pt.xy());    // 21

my_pt.color = 'red';
my_pt.color = 'blue';
console.log(my_pt.color);     // [ 'red', 'blue' ]

console.log(my_pt);     // Point { x: 3, y: 7, colors: [ 'red', 'blue' ] }

23、静态方法 static

无需实例化直接调用类里的方法
class Point {
    static colors(color){
        console.log(color);
    }
}

Point.colors('red');    // red

24、继承 exetends

class GroupA {
    constructor(name, age) {
        this.name = name;
        this.age = age
    }

    info() {
        return `${ this.name }, ${ this.age}`;
    }
}

class GroupB extends GroupA {
    constructor(name, age) {
        super(name, age);   // 调用父类的
    }
}

let my_group = new GroupB('张三', '26');
console.log(my_group.info());   // 张三, 26

25、Set

Set 存储任何类型的唯一值,不能有重复的内容。
let my_color = new Set('pink');
my_color.add('red');    // 添加
my_color.add('blue');
my_color.add('blue');    // 添加相同元素
my_color.forEach(item => {  // 遍历元素
    console.log(item);
});
//red
//blue
console.log(my_color);  // Set { 'red', 'blue' }
console.log(my_color.size);  // 查找有几个:2
console.log(my_color.has('red'));  // 查找是否包含:ture
my_color.delete('red');  // 删除其中一项
console.log(my_color);  // Set { 'blue' }
my_color.clear();   // 清空 Set
console.log(my_color);  // Set {}

26、Map

Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。
let my_edc = new Map();
let phone = {}, color = function() {}, pad = 'pad';

my_edc.set(phone, 'iPhone11');
my_edc.set(color, 'red');
my_edc.set(pad, 'iPad Pro');

console.log(my_edc);
// Map {
//     {} => 'iPhone11',
//     [Function: color] => 'red',
//     'pad' => 'iPad Pro'
// }

console.log(my_edc.size);   // 查找有几个:3
console.log(my_edc.get(phone));     // iPhone11
my_edc.delete(phone);     // 删除其中一项
console.log(my_edc.has(pad));     // 查找是否包含:true
my_edc.forEach((value, key) =>{
    console.log(`${ key } = ${ value }`);
});

// [object Object] = iPhone11
// function() {} = red
// pad = iPad Pro

my_edc.clear();   // 清空 Map
console.log(my_edc);  // Map {}

27、模块 Module

模块功能主要由两个命令构成:export 和 import。
  • export 命令用于规定模块的对外接口。
  • import 命令用于输入其他模块提供的功能。

一个模块就是一个独立的文件。该文件内部的所有变量,外部无法获取。如果你希望外部能够读取模块内部的某个变量,就必须使用export关键字输出该变量

export 可以输出变量或者函数:

// 输出变量:
export var year = 1958; 
// 或者写成:
var year = 1958; 
export {year};  //(推荐)

// 输出函数:
export function f() {};
// 或者写成:
function f() {}
export {f};

export default let now_date = '2020-01-22'; // 默认导出

import 导入:

import {year} from './modules/xxx.js'   // 导入 year
import * as xxx from './modules/xxx.js' // 导入全部 
import now_date from './modules/xxx.js'  // 默认导入

不要删除

小站不易,感谢支持!