箭头函数:
适当的省略函数中的function和return关键字
1.无参数,无返回值
function show(){
alert("hello world");
}
var show =()=>{
alert("hello world");
}
2.有参数,有返回值
function add(x){
return x +10;};
var add =x =>{
return x +10
}
3.多个参数,有返回值
function show(x,y){
alert(x+y);
}
var show =(x,y)=>{
alert(x+y);
}
var newArr =arr.filter(function(item){
return item>20;
});
var newArr =arr.filter(item=>item>20);
箭头函数需要注意的部分
1:箭头函数,不能用new
2.箭头,如果返回值是一个对象,一定要加();
3.箭头函数中的this,指向的是上一层函数的主人;
ver person ={
username:"钢铁侠",
show:function(){
person.username // 钢铁侠
this.username // 钢铁侠
}
show:() => {
alert(person.username);// 钢铁侠
alert(this.username) //undefind
}
}
闭包
满足以下特点叫做闭包
1.函数嵌套函数
2.内部函数使用外部函数的形参和变量
3.被引用的形参和变量就不会被[垃圾回收机制所回收]
好处:1希望一个变量常驻在内存当中
2避免全局污染
3可以声明私有成员
用法:1模块化代码
2在循环中直接找到对应元素的索引
var moduleA =(function(){
var count =10; //私有变量
function aaa(){ //私有方法
count +=2;
alert(count);
}
function bbb(){
count +=10;
alert(count);
}
return{
funcA:aaa,
funcB:bbb
}
})();
moduleA.funcA(); //12
moduleA.funcB(); //120