(一) 函数参数的扩展
默认参数
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 的时候,也不适合使用箭头函数。