ES6: Arrow Functions

栏目: JavaScript · 发布时间: 7年前

内容简介:由于

基本语法

(参数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

以上所述就是小编给大家介绍的《ES6: Arrow Functions》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Microformats

Microformats

John Allsopp / friends of ED / March 26, 2007 / $34.99

In this book, noted web developer and long time WaSP member John Allsop teaches all you need to know about the technology: what Microformats are currently available and how to use them; the general pr......一起来看看 《Microformats》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具