函数
//函数默认参数使不允许由同名参数 function fn(name,name,age){ //同名后边参数覆盖前面的 console.log(name,name); } fn("webcyh",21); function test(name,age=21){ console.log(name,age); } //当传递的参数不为空或者undefined则有效果 test("webcyh",undefined); test("webcyh",null); //不定参数 function test2(name,...values){ console.log(name); //不定参数返回的是数组 console.log(values); } test2("webcyh",1,2,2,2,2,2); //箭头函数 自执行 当箭头函数没有参数或者参数多个的时候需要括号 //当函数只有一条语句且有返回值 可以不需要花括号 //当返回值为对象 需要添加() (()=>console.log("hello"))(); var f = v=>v; console.log(f(1)); //箭头函数 没有 this、super、arguments 和 new.target 绑定。 //this指向在外边的this 而且不能作为构造函数 不能使用new console.log((()=>({name:"webcyh",age:21}))()); function test3(){ setInterval(()=>{ console.log(this.a); },1000); }; test3.call({a:"webcyh"});
在这里this指向外边的this好处
this 对象一直很令人头大,回调函数,经常看到 var self = this 这样的代码,为了将外部 this 传递到回调函数中,那么有了箭头函数,就不需要这样做了,直接使用 this 就行
const test = { age:21, getAge:()=>console.log(this.age) } const test1 = { age:21, getAge(){ console.log(this.age); } } var age = 1; test.getAge(); test1.getAge(); //注意在监听点击事件的时候可能导致无法绑定到相应的元素上面