zoukankan      html  css  js  c++  java
  • ES6箭头函数

    * 箭头函数的特点:
    1、简洁
    2、箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
    3、扩展理解: 箭头函数的this看外层的是否有函数,
    如果有,外层函数的this就是内部箭头函数的this,
    如果没有,则this是window。

    * 作用: 定义匿名函数
    * 基本语法:
    * 没有参数: () => console.log('xxxx')
    * 一个参数: i => i+2
    * 大于一个参数: (i,j) => i+j
    * 函数体不用大括号: 默认返回结果
    * 函数体如果有多个语句, 需要用{}包围,若有需要返回的内容,需要手动返回
    * 使用场景: 多用来定义回调函数

    没有形参,并且函数只有一条语句

         let fun1=()=>console.log('fun1()');
         fun1();

     一个形参,并且函数体只有一条语句

     let fun2 = x => x;
     console.log(fun2(5));

     形参是一个以上

        let fun3 = (x, y) => x + y;
        console.log(fun3(25, 39))

    函数体有多条语句

     let fun4 = (x, y) => {
            console.log(x, y);
            return x + y;
        };
        console.log(fun4(34, 48));//82
    
        setTimeout(() => {
            console.log(this);
        },1000)

    箭头函数this指向

     let btn = document.getElementById('btn');
     btn.onclick = function () {
           console.log(this);//btn
       };
    
    let btn2 = document.getElementById('btn2');
    let obj = {
            name : 'kobe',
            age : 39,
            getName : () => {
                btn2.onclick = () => {
                    console.log(this);//window
                };
            }
        };
        obj.getName();
     function Person() {
         this.obj = {
             showThis : () => {
                 console.log(this);
             }
         }
     }
        let fun5 = new Person();
        fun5.obj.showThis();//Person
  • 相关阅读:
    python 三方面库整理
    windows MYSQL 安装及修改root密码
    TCP 套叠字
    自动化谷歌浏览驱动
    python os
    python 协程
    python GIL :全局解释器
    python 多进程
    python 多线程
    python 3 往Excel 中的写入内容但不覆盖原内容
  • 原文地址:https://www.cnblogs.com/hack-ing/p/12005864.html
Copyright © 2011-2022 走看看