美文网首页
箭头函数 笔记

箭头函数 笔记

作者: xingkong_s | 来源:发表于2018-12-12 10:35 被阅读6次
为什么引入箭头函数

this 太难用了

let constroller = {
  el:"body",
  name:"xingkongs",
  init:function(){
   $(this.el).on("click",function(){
        this.getName()
    }.bind(this))
  },
  init2:function(){
    $("main").on("click",this.sayHi)
  },
  getName:function(){
    console.log(this.name)
  },
   sayHi:function(){
    console.log("hi")
  }
}
constroller.init() //xingkongs
constroller.init2()  // hi   xingkongs

this是call()的第一个参数
既然是参数 它是什么就得看(function)函数如何调用的,
谁调用了函数 this就是谁, 没人调用 那就默认是 window

var Obj = {
    function xxx(){
      console.log(this)
    }
}
Obj.xxx.()  //Obj

以前的函数永远保留了一个潜在的参数this,这个参数你只能用call来指定

function foo(/*this,*/p1,p2){
    //let this = arguments[-1]
    let p1 = arguments[0]
    let p2 = arguments[1]
}
foo(1,2)  //函数调用的小白写法
//this === window p1 === 1  p2===2
foo.call({name:xingkongs},1,2)  //函数调用的高级写法
//this === {name:xingkongs} p1 === 1 p2 === 2

既然this这么难用 箭头函数就去掉了this参数(函数中默认隐式添加的)
箭头函数没有任何隐藏的参数
如果你用this 那你就需要像参数一样传进去

let controller = {
  el:"#app",
  name:"xingkongs",
  init:(self)=>{
    self.getName()
  },
  getName:()=>{
    console.log(this.name)
  }
}
controller.init(controller)

箭头函数调用时没有this这个隐藏参数
那我能还能用call传入this的值吗? 不能!! 外面 this是什么里面 this就是什么

console.log(this)  // window
let foo3 = (p1,p2)=>{
    console.log(this)
}
foo3.call({name:"xingkongs"}) //window
箭头函数 语法

标准

let f = (p1,p2) => {
  console.log("...")
  return p1+p2
}

一个参数 可以简写成

let f1 = p1 => { console.log("...") return p1*2}

一个参数 只返回return 可以简写成

let f2 = p2 => p2*2
为什么会用=> 这个语法?

coffeeScript 中出现了 fat arrow x=>{x*2} ,ES觉得好用就借用了过来

相关文章

  • 箭头函数 笔记

    为什么引入箭头函数 this 太难用了 this是call()的第一个参数既然是参数 它是什么就得看(functi...

  • ES6~箭头函数

    什么是箭头函数 单表达式箭头函数 相当于 多表达式箭头函数 箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有...

  • 箭头函数和立即执行函数

    箭头函数 箭头函数和普通函数有什么区别?如果把箭头函数转换为不用箭头函数的形式,如何转换主要是this的差别,箭头...

  • 学习 ES 6 箭头函数

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

  • 箭头函数

    箭头函数 箭头函数能让this的指向固定化 分析:1)第一个setInterval()中使用了箭头函数,箭头函数使...

  • TS  笔记this

    this 箭头函数在箭头函数创建的地方获得this;非箭头函数,在调用函数的地方获得this如图

  • 箭头函数和数组

    箭头函数&数组 箭头函数 特点: 没有 this 没有 arguments 没有prototype在箭头函数中使用...

  • 箭头函数

    箭头函数 为什么使用箭头函数

  • 箭头函数中this的指向

    箭头函数在平时开发中用着非常爽,箭头函数有什么特点呢 箭头函数不能够当做构造函数使用 箭头函数没有argument...

  • js学习笔记4(函数)

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

网友评论

      本文标题:箭头函数 笔记

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