27

ES6: Arrow Functions

 4 years ago
source link: https://www.tuicool.com/articles/qE3Anqm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

基本语法

(参数1, 参数2..., 参数n) => {函数声明}

单一参数 => { 函数声明 }   

(参数1, 参数2...) => 单一表达式

() => { 函数声明 }

与一般 function 的区别

  • 箭头函数中的 this 指向的是定义时的对象,而不是使用时的对象 
// 事件绑定
document.body.addEventListener('click', () => {
     console.log(this)  // Window Object
})
document.body.addEventListener('click', function(){
   console.log(this)  // body object
})

// 对象中的方法
var a = {
   name: 'a',
   getname: () => {
       console.log(this)
   }
}
a.getname()  // Window

var a = {
    name: 'a',
    getname: function(){
        console.log(this)
    }
}
a.getname() // {name: "a", getname: ƒ}
  • 通过 call 或 apply 调用   

由于 箭头函数没有自己的this指针 ,通过  call()  或 apply() 方法调用一个函数时,只能传递参数,他们的第一个参数会被忽略

let f = (val) => {
    console.log(this);
    console.log(val);
}
let obj = { count: 1};
f.call(obj, 'test')

输出: Window
      test
  •  不可以使用 arguments 对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替
let fn = (a, b) => {
    console.log(arguments)  // 报错
}

rest参数替代

let fn = (...rest) => {
    console.log(rest);
}

fn(1, 2);  // [1,2]
  •  不能用箭头函数定义构造函数,箭头函数不存在 prototype;因此也不能通过 new 关键字调用 
let FN = () => {}
console.log(FN.prototype)  // undefined

let fn = new FN();   // Uncaught TypeError: A is not a constructor

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK