箭头函数的使用

简写方法速记

将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数列表和函数体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function add(a,b){
return a+b;
}
//简写为:
(a,b)=>{//删掉了function和函数名
return a+b;
}

var add = function(a,b){
return a+b;
}
//简写为:
var add = (a,b)=>{ //删掉了function
return a+b;
}

箭头函数的书写规则

箭头函数的书写 ()=>{}

1
2
3
4
const test = (zjcopy) => { 
console.log(zjcopy)
}
test('hello')

箭头函数简写规则:

(1)箭头函数只能用赋值式写法,不能用声明式写法

1
2
3
let f = (a) => {
return a
}

(2)如果参数只有一个,可以不加括号,如果没有参数或者参数多于一个就需要加括号

1
2
3
let f = a => {
return a
}

(3)如果函数体只有一句话,可以省略函数体大括号

1
let f = a => return a

(4)箭头函数返回对象时,省略大括号,用小括号括起来。

箭头后面return的是一个对象时, 需要使用({});

(5)如果函数体只有一句话,并且这一句话是return 返回值 那return也可以要省略

1
2
let f = a => a
f(2) // 2

箭头函数的特点

1.箭头函数没有自己的this,arguments,super或new.target

2.箭头函数不绑定this,会捕获其所在上下文的this,作为自己的this。

这句话需要注意的是,箭头函数的外层如果有普通函数,那么箭头函数的this就是这个外层的普通函数的this,箭头函数的外层如果没有普通函数,那么箭头函数的this就是全局变量。

3. 箭头函数是匿名函数,不能作为构造函数,不可以使用new命令,否则后抛出错误。

4. 箭头函数不绑定arguments,取而代之用rest参数解决,同时没有super和new.target。

箭头函数没有arguments、super、new.target的绑定,这些值由外围最近一层非箭头函数决定。

外围最近一层非箭头函数指的是箭头函数被包裹在一个普通函数中

5.箭头函数可以通过拓展运算符获取传入的参数。

image.png

6. 使用call,apply,bind并不会改变箭头函数中的this指向。

  • 当对箭头函数使用call或apply方法时,只会传入参数并调用函数,并不会改变箭头函数中this的指向。
  • 当对箭头函数使用bind方法时,只会返回一个预设参数的新函数,并不会改变这个新函数的this指向。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.name = "window_name";

let f1 = function () {
return this.name;
};
let f2 = () => this.name;

let obj = { name: "obj_name" };

console.log(f1.call(obj)); //obj_name
console.log(f2.call(obj)); // window_name
console.log(f1.apply(obj)); // obj_name
console.log(f2.apply(obj)); // window_name
console.log(f1.bind(obj)()); // obj_name
console.log(f2.bind(obj)()); // window_name

7. 箭头函数没有原型对象prototype这个属性

由于不可以通过new关键字调用,所以没有构建原型的需求,所以箭头函数没有prototype这个属性。

1
2
let F = ()=>{};
console.log(F.prototype) // undefined

8. 不能使用yield关键字,不能用作Generator函数

arguments函数

arguments有什么用?

arguments对象是所有非箭头函数中都可用的局部变量,可以使用arguments对象在函数中引用函数的参数,此对象包含传递给函数的每一个参数,第一个参数在索引0的位置。

如何将arguments对象转换为数组

  1. 通过slice
  2. 通过拓展运算符
  3. 通过Array.from
1
2
3
4
5
6
7
js
复制代码
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

const args = Array.from(arguments);
const args = [...arguments];

arguments函数如何调用自身函数?

我们先看看下面这个函数,这个是可以正常运行的。

1
2
3
4
5
function factorial (n) {
return !(n > 1) ? 1 : factorial(n - 1) * n;
}

[1,2,3,4,5].map(factorial);

但是作为匿名函数则不行。

1
2
3
[1,2,3,4,5].map(function (n) {
return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n;
});

因此arguments.callee诞生了。

1
2
3
[1,2,3,4,5].map(function (n) {
return !(n > 1) ? 1 : arguments.callee(n - 1) * n;
});

所以arguments要想调用自身的匿名函数,可以通过arguments.callee来调用。