美文网首页
ES6 箭头函数

ES6 箭头函数

作者: wulle__ | 来源:发表于2022-07-10 19:34 被阅读0次
普通函数:
  • 命名函数形式
    function fn1(a) {
      console.log(a);
    }
  • 字面量形式
    var fn2 = function (a) {
      console.log(a);
    };
箭头函数
    var fn3 = (a, b) => {
      console.log(a, b);
    };
    fn3(10, 11);

一个参数可以省略括号

    var fn4 = (a) => {
      console.log(a);
    };

没有参数的时候 不能省略括号

    var fn5 = () => {
      console.log(123);
    };

返回值

    function aa() {
      // 正常函数
      return 123;
    }
命名函数转箭头函数
    let aa1 = () => 123;箭头函数
    // 箭头函数中,如果只有一条 return 语句,则可以省略 大括号
    // 如果 这个箭头函数 还有且只有一个形参
    // 则小括号也可以省略
    // let aa1 = a => a + 1;

    function b(){
        return function (a){
            return a+1
        }
    }
    let b=()=>a=>a+1;
    let b1=b()(1);
    console.log(b1); // 2
命名函数与箭头函数中this的指向问题
    btn.onclick=function(){
        console.log(this);// 标签
    }

    btn1.onclick=()=>{
        console.log(this);// window
    }

一般绑定事件函数的时候 不要使用 箭头函数

    btn.onclick=function(){
        setInterval(function(){
            console.log(this);// window
        },3000);
    }

    btn1.onclick=function(){
        setInterval(()=>{
            console.log(this);// 标签
        },3000);
    }

当内部函数使用箭头函数时,不会改变外部函数的 this指向

    btn.onclick=function(){
        btn1.onclick=function(){
            console.log(this);// btn1
        }
        btn1.onclick=()=>{
            console.log(this);// btn
        }
    }
总结
  • 普通函数 谁调用我 我的this指向谁
  • 箭头函数 我被定义时 定义的环境中this指向谁 我的this就指向谁
对象中的箭头函数

给对象定义方法时,不要使用箭头函数

    let obj={
        say:function(){
            console.log(this);// obj
        },
        eat:()=>{
            console.log(this);// window
        }
    }
    obj.say();
    obj.eat();
    function Dog(){
        this.say=function(){
            console.log(this);// obj
        }
        this.eat=()=>{
            console.log(this);// obj
        }
    }
    let d1=new Dog();
    d1.say();
    d1.eat();

相关文章

  • ES6箭头函数简介

    @(JS技巧)[ES6|箭头函数] ES6箭头函数(Arrow Functions) ES6可以使用“箭头”(=>...

  • es6全家桶(二)—— 箭头函数

    es6全家桶(二)—— rest参数、箭头函数 箭头函数 ES6 允许使用“箭头”(=>)定义函数。 var f ...

  • es6、js、css、jquery、vue以及程序设计 知识点总

    es6 列举常用的es6特性。 箭头函数this的指向。 eg:箭头函数的特性 箭头函数内部没有construc...

  • 箭头函数

    ES6允许使用“箭头”(==>)定义函数。 箭头函数 等同于

  • 学习 ES 6 箭头函数

    箭头函数的用法 ES6 允许使用“箭头”(=>)定义函数。 箭头函数的一个用处是简化回调函数。 箭头函数 this...

  • JavaScript箭头函数

    ES6新语法箭头函数 箭头函数是ES6新语法,因为语法简单、可读性好,所以使用的也很多。箭头函数也是匿名函数,区别...

  • 关于ES6箭头this的指向问题

    ES6 允许使用 “ 箭头 ” (=>)定义函数。 箭头函数 填 坑。 this的指向是 向上查找 非箭头函数的...

  • ES6箭头函数(Arrow Functions)

    箭头函数是什么?(What) 箭头函数 (Arrow Functions)也称“胖箭头函数”,是ES6全新的特性。...

  • 2019-01-11

    ES6 箭头函数 箭头函数表示法:()=>console.log('Hello') 箭头函数和普通函数的区别 和普...

  • js学习笔记4(函数)

    1.箭头函数 ES6新增属性。箭头函数特别适合嵌入函数的场景。 箭头函数虽然语法简介,但是很多场合不适用。箭头函数...

网友评论

      本文标题:ES6 箭头函数

      本文链接:https://www.haomeiwen.com/subject/sdunbrtx.html