es6學習四:函式相關擴充套件
阿新 • • 發佈:2018-11-25
引數預設值:
before:
function foo(param){
let p = param || 'hello';
console.log(p);
}
foo('hi');
now:
function foo(param = 'nihao'){
console.log(param);
}
foo('hello kitty');
引數解構賦值:
function foo(uname='lisi',age=12){
console.log(uname,age);
}
foo('zhangsan',13);
function foo({uname='lisi',age=13}={}){ console.log(uname,age); } foo({uname:'zhangsan',age:15});
rest引數(剩餘引數):
function foo(a,b,...param){
console.log(a);
console.log(b);
console.log(param);
}
foo(1,2,3,4,5);
擴充套件運算子 (與上面相反)...:
before:
function foo(a,b,c,d,e,f,g){
console.log(a + b + c + d + e + f + g);
}
let arr = [1,2,3,4,5,6,7];
foo.apply(null,arr);
now:
function foo(a,b,c,d,e,f,g){
console.log(a + b + c + d + e + f + g);
}
let arr = [1,2,3,4,5,6,7];
foo(...arr);
應用(合併陣列):
// 合併陣列
let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr3 = [...arr1,...arr2];//擴充套件運算子相當於把陣列拆開了
console.log(arr3);
箭頭函式:
基本使用:
- 函式無引數:
before:
function foo(){ console.log('hello'); } foo();
now:
let foo = () => console.log('hello');
foo();
- 函式有1個引數
before:
function foo(v){
return v;
}
let ret = foo(111);
console.log(ret);
now:
function foo(v){
return v;
}
let foo = v => v;
- 函式有多個引數
let foo = (a,b) => {let c = 1; console.log(a + b + c);}
foo(1,2);
- 匿名函式
let arr = [123,456,789];
arr.forEach(function(element,index){
console.log(element,index);
});
arr.forEach((element,index)=>{
console.log(element,index);
});
注意事項:
1、箭頭函式中this取決於函式的定義,而不是呼叫
function foo(){
// 使用call呼叫foo時,這裡的this其實就是call的第一個引數
// console.log(this);
setTimeout(()=>{
console.log(this.num);
},100);
setTimeout(function(){
console.log(this.num);
},200);
}
foo.call({num:1});
2、箭頭函式不可以new,不可以作為建構函式
let foo = () => { this.num = 123;};
new foo();
3、箭頭函式不可以使用arguments獲取引數列表,可以使用rest引數代替
let foo = function(a,b){
console.log(a,b);
console.log(arguments);//這種方式獲取不到實參列表
}
foo(123,456);
let foo = (a,b) => {
console.log(a,b);
console.log(arguments);//這種方式獲取不到實參列表
}
foo(123,456);
通過rest引數:
let foo = (...param) => {
console.log(param);
}
foo(123,456 );