箭头函数

114 阅读1分钟

【箭头函数】

 普通函数 

function fn() { return 123 }

let a = fn();

console.log(a);

function fn(str) {

let msg = str + 'hello'

return msg;

}

let a = fn('张三丰');

console.log(a);

=>箭头函数后面只有一段表达式代表 return 返回

let fn = () => 123;

let a = fn();

console.log(a);

箭头函数只有一个参数()可以省略不写

普通函数可以作为构造函数,箭头函数不能作为构造函数不然会报错

let fn = (str) => {

let msg = str + 'hello'

return msg;

};

let a = fn('张无忌');

console.log(a);

普通函数this谁调用就是谁的,箭头函数没有自己的this,箭头函数的this是上下文环境的this

let obj1 = {

name:"张三",

fn:function(){

console.log(this)

}

}

let obj2 = {

name:"李四",

}

普通函数的this可以被call 或apply修改

obj1.fn.call(obj2) 

 一个参数都没有箭头不能省略 

let obj1 = {

name:"张三",

fn:()=>{

 目前的环境下的this是window 

console.log(this);

}

}

let obj2 = {

name:"李四",

}

obj1.fn()

 this指向window 当前上下文环境

箭头函数的this不会被call 或者apply 修改 

obj1.fn.call(obj2)