• es6的几种写法


    语法:
    1、只有一个参数,可以不用写小括号:

    var single = a => a; //相当于var single = function(a){return a;}
    console.log(single('hello, world'))// 'hello, world'
    var single = a => console.log(a); //相当于var single = function(a){console.log(a);}
    single('hello, world') // 'hello, world'

    2、没有参数,要写一个空的小括号:

    var noPare = () => console.log("No parameters");
    noPare(); //"No parameters"
    3、多个参数,参数在小括号中用逗号隔开:

    var mulPare = (a,b) => console.log(a+b);
    mulPare(1,2); // 3
    4、函数体有多条语句,用大括号包起来:

    var differ = (a,b) => {
         if (a > b) {
              return a - b
         } else {
              return b - a
         }
    };
    differ(5,3); // 2
    5、返回对象时需要用小括号包起来,因为大括号被占用解释为代码块了:

    var getObject = object => {
    // ...
    return ({
    name: 'Jack',
    age: 33
    })
    }
    6、直接作为事件,单条语句也要用大括号包起来:

    form.addEventListener('input', val => {
    console.log(val);
    });
    7、作为数组排序回调,单条语句也要用大括号包起来:

    var arr = [1, 9 , 2, 4, 3, 8].sort((x, y) => {
    return x - y ;
    })
    console.log(arr); // 1 2 3 4 8 9
    注意:
    1、与普通function实例没有区别,通过 typeof 和 instanceof 都可以判断它是一个function

    var fn = a => console.log(a);
    console.log(typeof fn); // function
    console.log(fn instanceof Function); // true
    2、this固定,不需要再多写一句var _this = this;去绑定this指向

    fruits = {
    data: ['apple', 'banner'],
    init: function() {
    document.onclick = ev => {
    alert(this.data)
    }
    }
    }
    fruits.init(); // ['apple', 'banner']
    3、箭头函数不能用new

    var Person = (name, age) => {
    this.name = name
    this.age = age
    }
    var p = new Person('John', 33) // error

  • 相关阅读:
    【如何在mysql 官网下载最新版本mysql 数据库】
    【17-类加载与反射】
    【16-网络编程】
    【14-输入/输出】
    【13-Annotation】
    【12-JDBC编程】
    C# SqlHelper类的数据库操作
    C# DateTime与时间戳转换
    C#递归方法遍历目录及子目录
    C# SaveFileDialog的用法
  • 原文地址:https://www.cnblogs.com/fdbjazy/p/10151703.html
Copyright © 2020-2023  润新知