箭头函数
ES6中新增的定义函数的语法 () => { }
//箭头函数是用来简化函数定义语法的 ()=>{}
const fn = () => {
console.log(123);
}
fn(); //123
函数体中只有一句代码,且代码的执行结果就是函数的返回值,函数体大括号{ }可以省略。
//函数体中只有一句代码,且代码的执行结果就是函数的返回值,可以省略大括号
function sum(num1, num2) {
return num1 + num2;
}
const sum = (num1, num2) => num1 + num2;
const result = sum(10, 20);
console.log(result);
在箭头函数中 如果形参只有一个 形参外侧的小括号也是可以省略的。
const fn = v => alert(v);
fn(20);
箭头函数不绑定this 箭头函数没有自己的this关键字。
如果在箭头函数中使用this,this关键字将指向箭头函数定义位置中的this。
//箭头函数不绑定this 箭头函数没有自己的this关键字
//如果在箭头函数中使用this
//this关键字将指向箭头函数定义位置中的this
const obj = {
name: '张三'
}
function fn() {
console.log(this);//{name: "张三"}
return () => {
console.log(this);//{name: "张三"}
}
}
const resFn = fn.call(obj);//resFn 相当于 上面代码 匿名函数的名字
resFn();
var age = 100;
var obj = {
age: 20,
say: () => {
alert(this.age); //undefined
}
}
obj.say();
箭头函数没有自己的this,箭头函数当中的this指向箭头函数定义区域的 this
当前箭头函数定义在了obj这个对象里面,但是obj是个对象,不能产生作用域,
所以箭头函数实际定义在了全局作用域,所以当我们使用say方法的时候this指向的是window
window下面没有age属性 所以是undefined
剩余参数
这个语法允许我们将一个不定数量的参数表示为一个数组。
function sum(first,...args){
console.log(first); // 10
console.log(args); // [20, 30]
}
sum(10, 20, 30)
const sum = (...args) => {
let total = 0;
args.forEach(item => total += item);
return total;
}
console.log(sum(10, 20)); //30
console.log(sum(10, 20, 30)); //60
剩余参数和解构配合使用:
let students = ['wangwu', 'zhangsn', 'lisi'];
let [s1, ...s2] = students;
console.log(s1); //wangwu
console.log(s2); //["zhangsn", "lisi"]