基本结构:箭头函数左边是参数,右边是返回值
//创建func函数
let func = num => num;
//上面的func函数等价于
let oldFunc = function (num) {
return num
};//如果存在多个参数,参数需要括号包起来
let sum = (num1, num2) => num1 + num2;
//上面的sum函数等价于
let oldSum = function (num1, num2) {
return num1 + num2;
};//如果返回值需要大量逻辑,并且一个表达式写不完,需要用花括号包起来返回体
let chkUsername = username => {
if (username == 'zhang') {
return 1;
} else if (username == 'li') {
return 2;
} else {
return 3;
}
}//箭头函数的返回值支持使用已定义的函数
let getInt = num => parseInt(num);
//箭头函数的this,这是以前this的作用域,在函数中创建闭包,此时的this变了
let userAge = {
age: 1,
getAge: function () {
var fn = function () {
return this.age //此时的this指向的是windows
}
return fn();
},
setAge: function (age) {
this.age = age;
}
};
userAge.setAge(19);
console.log(userAge.getAge())//箭头函数this总是指向词法作用域,也就是外层调用者obj
let userNewAge = {
age: 1,
getAge: function () {
let fn = ()=>(this.age)
return fn();
},
setAge: function (age) {
this.age = age;
}
};
userNewAge.setAge(19);
console.log(userNewAge.getAge())