0. ES6新增的定义函数的方式
// 简化函数定义语法
const fn = () => {
console.log(123);
}
fn();
1. 函数体中只有一句代码,且代码的执行的结果就是返回值,可以省略大括号
function sum(a, b) {
return a + b;
}
const sum = (num1, num2) => num1 + num2;
2. 如果函数参数只有一个,可以省略小括号
function fn(v) {
return v;
}
const fn = v => v * v;
3. this在箭头函数中的定义
箭头函数不绑定this箭头函数没有自己的this
关键字如果在箭头函数中使用this,
this关键字将指向箭头函数定义位置中的this
function fn() {
console.log(this);
return () => {
console.log(this);
}
}
const obj = {
name: '张三'
};
fn()(); // window window
fnr = fn.call(obj);
fnr(); // obj obj
4. 箭头函数在对象中的指向
ar obj = {
age: 20,
say: () => {
console.log(this); //this指向的是window
},
what: function() {
console.log(this); //这里的this指向的是obj
}
}
obj.say();
obj.what();