1.浅谈箭头函数 x=>与function(x){}
1.1. 执行效果等价(匿名函数)
代码实例
//完整格式
const s = new Set();
[2,3,5,4,5,2,2].forEach(function(x) {s.add(x)});
// Set结构不会添加重复的值
for(let i of s) {
console.log(i);
}
//语法糖格式
const s = new Set();
[2,3,5,4,5,2,2].forEach((x) =>s.add(x));
// Set结构不会添加重复的值
for(let i of s) {
console.log(i);
}
//简略格式
const s = new Set();
[2,3,5,4,5,2,2].forEach(x =>s.add(x));
// Set结构不会添加重复的值
for(let i of s) {
console.log(i);
}
1.2箭头函数()=>与function的区别
1.2.1 定义方式(有名函数)
var sum = (a,b) =>{a+b};这么写函数定义不成功
var fun = x=>{(x+2)};// fun(3) ;undefined
var fun = x=>{return (x+2)};//ok
var fun = x=>(x+2);//ok
故,当里面需要()时,外面括号用{},当只有一个括号时用()或者{return …}
//function
function sum(a,b){
return a+b;
}
//arrow function
var sum = (a,b) =>(a+b);
var sum = (a,b) =>{return a+b};
1.2.2 this的指向
tip1: function定义的函数,调用时this随着调用环境变化,而箭头函数this指向固定指向定义函数的环境
//使用function
function fun(){
console.log(this);
}
//定义一个对象
var obj = {aa:fun};
fun();//window
//这里调用的是方法故aa()
obj.aa();//object
//使用箭头函数
var fun = ()=>{console.log(this)};
var obj = {aa:fun};
fun();//window
obj.aa();//window
tip2: 箭头函数this是词法作用域,在编写时就已经确定好了。而匿名函数的this指向运行时实际调用的对象。
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100 this:Test
setTimeout(function(){
console.log(this.num); //undefined this:window
}, 500);
};
}
var obj = new Test();
obj.func();
//箭头函数以前这么干,利用闭包的概念,箭头函数可以看做这种方式的语法糖
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100
var that = this;
setTimeout(function(){
console.log(that.num); // 100
}, 500);
};
}
var obj = new Test();
obj.func();
//箭头函数
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100
setTimeout(() => {
console.log(this.num); // 100
}, 500);
};
}
var obj = new Test();
obj.func();
1.2.3构造函数
tip3:箭头函数除了传入的参数之外,其它的对象都没有!在箭头函数引用了this、arguments或者参数之外的变量,那它们一定不是箭头函数本身包含的,而是从父级作用域继承的。
- 不可以当做构造函数,也就是说,不可以使用 new 命令,否则会抛出错误。
- this、arguments、caller等对象在函数体内都不存在。
- 不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。
//使用function方法定义构造函数
function Person(name, age){
this.name = name;
this.age = age;
}
var lenhart = new Person('lenhart', 25);
console.log(lenhart);
//尝试使用箭头函数
var Person = (name, age) =>{
this.name = name;
this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor
1.2.4变量提升
tip4:由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let const定义的时候更不必说)关键词,而var所定义的变量不能得到变量提升,故箭头函数一定要定义于调用之前!
function foo(){
console.log('123');//123
}
//先调用,后定义
arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
console.log('456');
};
//先定义,再调用
var arrowFn = () => {
console.log('456');
};
arrowFn(); //456