关于javascript:js箭头函数使用

3次阅读

共计 891 个字符,预计需要花费 3 分钟才能阅读完成。

箭头函数应用

简化回调函数,简化函数表达式,固定 this 指向

arr.map(function(x) {return x * 2;})

arr.map((x) => 2 * x)
  • 没有本人的 this,无奈通过 call、apply、bind 扭转 this 指向
  • 没有 arguments 对象
  • 没有 protoType 属性
  • 没有 [[Construct]] 办法,不能被 new 调用,没有 new.target 绑定
 const fn1 = () => {console.log('arguments', arguments)
 }
 fn1(100, 200)  // error
   
 function fn2(){console.log('arguments', arguments)
 }
 fn2(100, 200)  // [100, 200, callee: ƒ, Symbol(Symbol.iterator): ƒ]

防止如下场景

  1. 对象办法(原型办法)
  2. 构造函数申明

    构造函数是通过 new 关键字来生成对象实例,生成对象实例的过程也是通过构造函数给实例绑定 this 的过程,而箭头函数没有本人的 this。因而不能应用箭头作为构造函数,也就不能通过 new 操作符来调用箭头函数

  3. 事件监听回调
  4. vue 选项式 api(生命周期、数据等)

留神:react 组件中能够应用箭头函数

Vue 组件实质上是一个 JS 对象;React 组件(非 Hooks)他实质上是一个 ES6 的 class

class Man {constructor(name, city) {
        this.name = name
        this.city = city
    }
    getName = () => {return this.name}
}
const f = new Man('李四','上海')
console.log(f.getName())   // 李四

嵌套箭头函数

管道机制部署

const pipeline = (...funcs) =>
  val => funcs.reduce((a, b) => b(a), val);

const plus = a => a + 1;
const multiply = a => a * 2;
const addThenMultiply = pipeline(plus, multiply);

addThenMultiply(5)   // 12
正文完
 0