• ES6常用语法(二)


    arrow functions (箭头函数)

    函数的快捷写法。不需要 function 关键字来创建函数,省略 return 关键字,继承当前上下文的 this 关键字

    // ES5
    
    var arr1 = [1, 2, 3];
    
    var newArr1 = arr1.map(function(x) {
    
      return x + 1;
    
    });
    
     
    
    // ES6
    
    let arr2 = [1, 2, 3];
    
    let newArr2 = arr2.map((x) => {
    
      x + 1
    
    });

    注意:当你的函数有且仅有一个参数的时候,是可以省略掉括号的;当函数中有且仅有一个表达式的时候可以省略{}

    let arr2 = [1, 2, 3];
    
    let newArr2 = arr2.map(x => x + 1);

    JavaScript语言的this对象一直是一比较麻烦的问题,运行上面的代码会报错,这是因为setTimeout中的this指向的是全局对象。

    class Animal {
    
        constructor() {
    
            this.type = 'animal';
    
        }
    
        says(say) {
    
            setTimeout(function() {
    
                console.log(this.type + ' says ' + say);
    
            }, 1000);
    
        }
    
    } 
    
    var animal = new Animal();
    
    animal.says('hi'); //undefined says hi
    
    
    解决办法:
    
    // 方法1: 将this传给self,再用self来指代this
    
    says(say) {
    
        var self = this;
    
        setTimeout(function() {
    
            console.log(self.type + ' says ' + say);
    
        }, 1000);
    
    }
    
    // 方法2: 用bind(this),即
    
    says(say) {
    
        setTimeout(function() {
    
            console.log(this.type + ' says ' + say);
    
        }.bind(this), 1000);
    
    }
    
    // ES6: 箭头函数
    
    // 当使用箭头函数时,函数体内的this对象,就是定义时所在的对象
    
    says(say) {
    
        setTimeout(() => {
    
            console.log(this.type + ' says ' + say);
    
        }, 1000);
    
    }

    template string (模板字符串)

    解决了 ES5 在字符串功能上的难点。

    第一个用途:字符串拼接。将表达式嵌入字符串中进行拼接,用 ` 和${}`来界定。

    // es5
    
    var name1 = "bai";
    
    console.log('hello' + name1);
    
     
    
    // es6
    
    const name2 = "ming";
    
    console.log(`hello${name2}`);

    用途二:在ES5时我们通过反斜杠来做多行字符串拼接。ES6反引号 “ 直接搞定。

    // es5
    
    var msg = "Hi 
    
    man!";
    
     
    
    // es6
    
    const template = `<div>
    
        <span>hello world</span>
    
    </div>`;

    destructuring (解构)

    简化数组和对象中信息的提取。

    ES6前,我们一个一个获取对象信息;ES6后,解构能让我们从对象或者数组里取出数据存为变量

    // ES5
    
    var people1 = {
    
      name: 'bai',
    
      age: 20,
    
      color: ['red', 'blue']
    
    };
    
    var myName = people1.name;
    
    var myAge = people1.age;
    
    var myColor = people1.color[0];
    
    console.log(myName + '----' + myAge + '----' + myColor); 
    
    // ES6
    
    let people2 = {
    
      name: 'ming',
    
      age: 20,
    
      color: ['red', 'blue']
    
    }
    
    let { name, age } = people2;
    
    let [first, second] = people2.color;
    
    console.log(`${name}----${age}----${first}`);

    default 函数默认参数

     
    
    // ES5 给函数定义参数默认值
    
    function foo(num) {
    
      num = num || 200;
    
      return num;
    
    }
    
     
    
    // ES6
    
    function foo(num = 200) {
    
      return num;
    
    }

    rest arguments (rest参数)

    解决了 es5 复杂的 arguments 问题

    function foo(x, y, ...rest) {
    
        return ((x + y) * rest.length);
    
    }
    
    foo(1, 2, 'hello', true, 7); // 9
    
     

    Spread Operator (展开运算符)

    用途一:组装数组

    let color = ['red', 'yellow'];
    
    let colorful = [...color, 'green', 'blue'];
    
    console.log(colorful); // ["red", "yellow", "green", "blue"]

    用途二:获取数组除了某几项的其他项

    let num = [1, 3, 5, 7, 9];
    
    let [first, second, ...rest] = num;
    
    console.log(rest); // [5, 7, 9]

     

    对象

    对象初始化简写

    // ES5
    
    function people(name, age) {
    
      return {
    
        name: name,
    
        age: age
    
      };
    
    }
    
     
    
    // ES6
    
    function people(name, age) {
    
      return {
    
        name,
    
        age
    
      };
    
    }

    对象字面量简写(省略冒号与 function 关键字)

    // ES5
    
    var people1 = {
    
      name: 'bai',
    
      getName: function () {
    
        console.log(this.name);
    
      }
    
    };
    
     
    
    // ES6
    
    let people2 = {
    
      name: 'bai',
    
      getName () {
    
        console.log(this.name);
    
      }
    
    };

    Promise

    用同步的方式去写异步代码

    // 发起异步请求
    
    fetch('/api/todos')
    
      .then(res => res.json())
    
      .then(data => ({
    
        data
    
      }))
    
      .catch(err => ({
    
        err
    
      }));

    Generators

    生成器( generator)是能返回一个迭代器的函数。

    生成器函数也是一种函数,最直观的表现就是比普通的function多了个星号*,在其函数体内可以使用yield关键字,有意思的是函数会在每个yield后暂停。这里生活中有一个比较形象的例子。咱们到银行办理业务时候都得向大厅的机器取一张排队号。你拿到你的排队号,机器并不会自动为你再出下一张票。也就是说取票机“暂停”住了,直到下一个人再次唤起才会继续吐票。

    迭代器:当你调用一个generator时,它将返回一个迭代器对象。这个迭代器对象拥有一个叫做next的方法来帮助你重启generator函数并得到下一个值。next方法不仅返回值,它返回的对象具有两个属性:done和value。value是你获得的值,done用来表明你的generator是否已经停止提供值。继续用刚刚取票的例子,每张排队号就是这里的value,打印票的纸是否用完就这是这里的done。

    // 生成器
    
    function *createIterator() {
    
      yield 1;
    
      yield 2;
    
      yield 3;
    
    }
    
     
    
    // 生成器能像正规函数那样被调用,但会返回一个迭代器
    
    let iterator = createIterator();
    
     
    
    console.log(iterator.next().value); // 1
    
    console.log(iterator.next().value); // 2
    
    console.log(iterator.next().value); // 3
    
     
  • 相关阅读:
    mount: error mounting /dev/root on /sysroot as ext3: Invalid argument
    redhat5.8 alt+ctrl+f1 黑屏
    Linux U盘 启动盘
    Debian For ARM Webmin Server
    Debian For ARM mysql-server install information
    fakeroot: preload library `libfakeroot.so' not found, aborting.
    FAT-fs (mmcblk0p1): Volume was not properly unmounted. Some data may be corrupt. Please run fsck.
    JavaScript获取table中某一列的值的方法
    SpringMvc(注解)上传文件的简单例子
    SpringMVC单文件上传、多文件上传、文件列表显示、文件下载
  • 原文地址:https://www.cnblogs.com/hjy-21/p/12364742.html
Copyright © 2020-2023  润新知