(一) 函數參數的擴展
默認參數
function fn(name,age=19){
console.log(name+","+age);
}
fn("ff");
fn("dd","20");
fn("hi","")
fn("hg",20)
注意點:使用函數默認參數時,不允許有同名參數。
//不報錯
function fn(name,name){
console.log(name);
}
function fn(name,name){
console.log(name);
}
fn("dd");//undefined
function fn(name,name,age=17){
console.log(name+","+age);
}
報錯SyntaxError: Duplicate parameter name not allowed in this context
只有在未傳遞參數,或者參數爲 undefined 時,纔會使用默認參數,null 值被認爲是有效的值傳遞。
function fn(name,age=17){
console.log(name+","+age);
}
fn("Amy",null); // Amy,null
函數參數默認值存在暫時性死區,在函數參數默認值表達式中,還未初始化賦值的參數值無法作爲其他參數的默認值。
function f(x,y=x){
console.log(x,y);
}
f(1); // 1 1
function f(x=y){
console.log(x);
}
f(); // ReferenceError: y is not defined
不定參數
不定參數用來表示不確定參數個數,形如,…變量名,由…加上一個具名參數標識符組成。具名參數只能放在參數組的最後,並且有且只有一個不定參數。
function fn(...values){
console.log(values.length)
}
fn(2);//2
fn(2,3,5,6,2,3)//6
箭頭函數
箭頭函數提供了一種更加簡潔的函數書寫方式。基本語法是:參數 => 函數體
var fn=a=>console.log(a);
fn(3);//3
var fn=(a,b)=>{console.log(a+b)}
fn(3,4);//7
當箭頭函數要返回對象的時候,爲了區分於代碼塊,要用 () 將對象包裹起來
var fn=(id,name)=>{console.log(({id:id,name:name}))}
fn(1,"lp")
注意點:箭頭函數沒有 this
、super
、arguments
和 new.target
綁定。
箭頭函數體中的 this 對象,是定義函數時的對象,而不是使用函數時的對象。
function fn(){
setTimeout(()=>{
// 定義時,this 綁定的是 fn 中的 this 對象
console.log(this.a);
},0)
}
var a = 20;
// fn 的 this 對象爲 {a: 19}
fn.call({a: 18}); // 18
箭頭函數不可以作爲構造函數,也就是不能使用 new 命令,否則會報錯
適合使用的場景
var Person = {
'age': 18,
'sayHello': function () {
setTimeout(function () {
console.log(this.age);
});
}
};
var age = 20;
Person.sayHello(); // 20
var Person1 = {
'age': 18,
'sayHello': function () {
setTimeout(()=>{
console.log(this.age);
});
}
};
var age = 20;
Person1.sayHello(); // 18
不適合使用的場景
定義函數的方法,且該方法中包含 this
var Person = {
'age': 18,
'sayHello': ()=>{
console.log(this.age);
}
};
var age = 20;
Person.sayHello(); // 20
// 此時 this 指向的是全局對象
var Person1 = {
'age': 18,
'sayHello': function () {
console.log(this.age);
}
};
var age = 20;
Person1.sayHello(); // 18
// 此時的 this 指向 Person1 對象
需要動態 this 的時候,也不適合使用箭頭函數。