箭头函数
//ES6 允许使用箭头(=>)定义函数
function fn(){
console.log('hello')
}
fn();
//箭头函数
//箭头函数是匿名函数,以下使用变量接收的
let main = ()=>{
// ()中用于存放形参
// {}中存放函数语句
console.log('hello')
}
//以下是是上方函数的调用方式
main();
//结果是一样的
箭头函数的 this 指向外层作用域的 this
let fn = () => {
console.log(this)//window
}
let obj = {
name : 'hello',
fn : () => {
console.log(this)//window
}
}
let obj2 = {
fn : function(){
let fn1 = () => {
console.log(this)//obj2
}
}
}
特性
- 箭头函数的this不能通过 call apply bind 修改指向
- 不能作为构造函数使用
- 不能使用 arguments(实参伪数组)
箭头函数简写
//当形参只有一个的时候可以不写小括号
let fn = (item)=>{
return item*item
}
let fn = item => {return item*item}
//当函数语句只有一行的时候可以不写大括号
let fn = item => item*item
console.log(fn(4))//16