文章目录
一、使用方法
- 箭头函数是ES6里面有个简写函数的语法方式
- 重点:箭头函数只能简写函数表达式,不能简写声明式函数
1.1、基本用法
function fn(){}; //不能简写
const fun = function(){}; //可以简写
let obj = {
fn :function(){}; //可以简写
}
- 语法:
(函数的形参) => {函数体内要执行的代码}
const fn = function(a,b){
console.log(a);
console.log(b);
}
//可以使用箭头函数简写成
const fun = (a,b) => {
console.log(a);
console.log(b);
}
const obj = {
fn : function(a,b){
console.log(a);
console.log(b);
}
}
//可以使用箭头函数简写成
const obj2 = {
fn : (a,b) =>{
console.log(a);
console.log(b);
}
}
1.2、简写写法
- 函数的形参只有一个的时候可以不写
()
其余情况必须写
const obj = {
fn : () => {
console.log('没有参数,必须写小括号');
},
fn2 : a => {
console.log('一个形参,可以不写小括号');
},
fn3 : (a,b) => {
console.log('两个或两个以上的参数,必须写小括号');
}
}
- 函数体只有一行代码的时候,可以不写
{}
,并且会自动return
const obj = {
fn : a => {
return a + 10;
},
fun : a => a + 10;
}
console.log(fn(10)); //20
console.log(fun(10)); //20
1.3、其他用法
传参默认值
- 我们在定义函数的时候,有的时候需要一个默认值出现
- 就是当我不传递参数的时候,使用默认值,传递参数了就使用传递的参数
function fn(a){
a = a || 10;
console.log(a);
}
fn(); //不传递参数的时候,函数内部的 a 就是 10
fn(20); //传递了参数 20 的时候,函数内部的 a 就是 20
- 在ES6中我们可以直接把默认值写在函数的形参位置
function fn(a = 10){
console.log(a);
}
fu(); // 不传递参数的时候,函数内部的 a 就是 10
fn(20); // 传递了参数 20 的时候,函数内部的 a 就是 20
- 这个默认值的方式箭头函数也可以使用
const fn = (a=10) => {
console.log(a);
}
fn(); // 不传递参数的时候,函数内部的 a 就是 10
fn(20); // 传递了参数 20 的时候,函数内部的 a 就是 20
- 注意:箭头函数如果你需要使用默认值的话,那么一个参数的时候也需要写()
作为方法使用
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log( this.i, this)
}
}
obj.b();
// undefined, Window{...}
obj.c();
// 10, Object {...}
通过 call 或 apply 调用
- 由于 箭头函数没有自己的this指针
- 通过 call() 或 apply() 方法调用一个函数时
- 只能传递参数,且它的第一个this执向参数会被忽略
var name = 'Rose';
var obj = {name:'Jack'};
function fun(){
console.log(this.name);
}
fun() // Rose
fun.call(obj); // Jack
fun.apply(obj); // Jack
var fn = ()=> console.log(this.name);
fn() // Rose
fn.call(obj); // Rose
fn.apply(obj); // Rose
二、其特殊性
2.1、没有 this
- 箭头函数内部没有 this ,箭头函数的 this 是上下文的 this
// 在箭头函数定义的位置往上数,这一行是可以打印 this 的
// 因为这里的 this 是window
// 所以箭头函数内部的 this 就是 window
const obj = {
fn : function(){
console.log(this);
},
//这个位置是箭头函数的上一行,但是不能打印出 this
fun : ()=>{
//箭头函数内部的 this 是书写箭头函数的上一行一个可以打印出 this 的位置
console.log(this);
}
}
obj.fn(); //Object
obj.fun(); //Window
- 按照我们之前的 this 指向来判断,两个都应该指向 obj
- 但是 fun 因为是箭头函数,使用this 不指向 obj ,而是指向 fun 的外侧obj的指向,就是 window
2.2、没有 super
- super指向的是当前对象的原型对象
var obj1 = {
method1() {
console.log("method 1");
}
}
var obj2 = {
method2:() =>{
super.method1(); // 报错:'super' keyword unexpected here
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2();
2.3、没有 prototype
var fn = () => {};
console.log(fn.prototype); // undefined
2.4、没有 arguments
- 箭头函数内部没有
arguments
这个参数集合
const obj = {
fn : function (){
console.log(arguments);
},
fun : (){
console.log(arguments);
}
}
obj.fn(1,2,3); //会打印一个伪数组[1,2,3]
obj.fun(1,2,3); //会直接报错
2.5、不能用作构造函数 (没 new)
var fn = () => {};
var fun = new fn(); // TypeError: fn is not a constructor