箭头函数
箭头函数 他是ES6的新语法 针对函数来说 现在应用非常广泛
在ES5中传统的函数体
function [函数名]([形参列表]){
函数体;
return 返回值;
}
函数名([实参列表])
在传统的函数中 相对来说比较麻烦
箭头函数简化了函数的编辑模式 主要的作用就是简单 灵活
箭头函数的结构
(形参列表)=>{
函数体
}
箭头函数和常规函数的区别是什么
1.箭头函数只能定义匿名函数
// 定义箭头函数
// 1.只能定义匿名函数
let fun1 = ()=>{
console.log('这是第一个箭头函数');
}
fun1();
2.箭头函数没有原型对象 不能定义构造
// 2.箭头函数没有原型对象 不能定义构造
function Car(name,color) {
this.name = name;
this.color = color;
}
let c = new Car('奥迪','黑色');
console.log(c);
// 使用箭头函数
let Cat = (name,color)=>{
this.name = name;
this.color = color;
console.log(this.color);
}
let a = new Cat('Tom','灰色'); //箭头函数 不是一个构造器
// a is not a constructor
3.箭头函数不能使用arguments new super
arguments主要的作用是传递不定参数使用 在箭头函数中无法使用
// 3.箭头函数中不能使用arguments
function fun2(){
console.log(arguments.length);
console.log(arguments);
// arguments.forEach(element => {
// console.log(arguments);
// });
// 判断数据类型
console.log(Object.prototype.toString.call(arguments));
}
fun2(1,2,3,4,5,6,7,8,9);
// 箭头函数使用arguments
let fun3 = ()=>{
console.log(arguments.length);
console.log(arguments);
}
fun3(1,2,3,4,5,6,7,8,9);
4.箭头函数特殊情况
a.只有一个参数的时候可以省略小括号
b.函数体只有一句话的时候 可以省略大括号
c.如果说函数体只有一句话 并且是返回值 省略大括号之后必须省略小括号
d.当省略大括号 返回值是对象的时候 需要使用小括号包裹
// 省略方式
// let fun1 = ()=>{
// console.log('你好 北京');
// }
// fun1();
// let fun2 = (m,n)=>{
// console.log('你好 北京');
// }
// fun2();
// 只有一个参数的时候 我们可以省略小括号(形参列表)
let fun3 = m=>{
console.log(m + 200);
}
fun3(200);
// 函数体只有一句话的时候 可以省略大括号
// let fun4 = ()=>{
// console.log('你好 朝阳');
// }
// fun4();
// 箭头函数省略大括号
let fun5 = ()=>console.log('你好 五方桥');
fun5();
// 如果说省略了大括号 但是这句话是返回值的时候
// let fun6 = ()=>{
// return '你好 中公';
// }
// console.log(fun6());
// 箭头函数省略return
let fun7 = ()=>'你好 优就业';
console.log(fun7());
// 如果说省略大括号 并且返回值是一个对象的时候 会出现错误
// let fun8 = ()=>{name : 'Eric',age : 18};
// console.log(fun8());
// 使用小括号包裹
let fun9 = ()=>({name : 'Eric',age : 18})
console.log(fun9());
5.箭头函数没有自己的this
// 箭头函数没有自己的this
let obj1 = {
name : 'Mary',
say : function(){
console.log(this);
}
}
obj1.say();
// 使用箭头函数
// let obj2 = {
// name : 'Eric',
// say : ()=>{
// console.log(this);
// }
// }
// obj2.say();
// let obj3 = {
// name : 'Eric',
// say : function(){
// return {
// name : 'MM',
// say : function () {
// console.log(this);
// }
// }
// }
// }
let obj3 = {
name : 'Eric',
say : function(){
return {
name : 'MM',
say : ()=>{
console.log(this);
}
}
}
}
obj3.say().say();