(精华)2020年7月4日 JavaScript高级篇 ES6(箭头函数)

    技术2026-03-16  3

    基本用法

    // 没有参数 多个参数 需要用() 包裹起来 const fn = ()=>5 console.log(fn()); const fnG = (num1,num2)=>num1 + num2 console.log(fnG(1,2)); // 函数块的语句 多于一条语句的 要使用{} 包裹起来 并且要用return 返回 const fJ = (a,b)=>{ let c = a+b; let d = c+19; return d } console.log(fJ(1,7)); // 注意 返回的是一个对象 {} 此时应该怎么处理 必须要在对象的外面加括号 let getObj = ()=>({name:'张三',age:18}) console.log(getObj()); let getObj1 = ()=>{ return { name:'张三',age:18 } } console.log(getObj1());

    注意点

    // 1 this 也是箭头函数作用最大的地方 this不再是动态的 定义时候所在的对象而不是使用时所在的对象 // 2 箭头函数不能当做构造函数 不能new // 3 箭头函数内部不能用 arguments // 4 不能够当做 generator函数 不能加yield命令

    实例演示

    // 见跑马灯的代码 function Person(){ this.name = '张三' this.say = function(){ console.log(`这是我的名字${this.name}`); } this.say = this.say.bind(this) // this.say = ()=>{ // console.log(`这是我的名字${this.name}`); // } } let person = new Person() let res = person.say res()

    使用时机

    // 箭头函数的使用时机 // 1 如果说有一个简短的语句 返回是一个简单的表达式 return num + num 2 函数内部没有this的引用 // 也没有自身的引用 (递归) // 2 内部需要 调用vat self = this 调用 bind 也适用于箭头函数 // 3 只要是回调函数 99% 用箭头函数就没有错

    不适用箭头函数的场景

    DOM 绑定的事件中调用 this 来获取自身的某个属性值

    document.querySelector('#textBtn').oninput = () => { console.log(this.value); // undefined };

    通过 call、apply、bind 来改变 箭头函数的 this

    // apply const A = (age, gender) => { this.age = age; this.gender = gender; }; const a = {}; A.apply(a, [18, 'gender']); console.log(a); // {} // bind const test = () => { console.log(this.gender); // window.gender => undefined }; const obj = { gender: 'male', }; const bindTest = test.bind(obj); bindTest();

    把箭头函数当做构造函数

    const A = () => {}; const a = new A(); // 报错

    在构造函数中使用 arguments 对象

    const a = () => { console.log(arguments); // arguments 未定义 };

    把箭头当做 generator 函数使用

    const a = *() => {}; // 编译器就语法错误了
    Processed: 0.014, SQL: 9