JS中的函数

1、函数形参的默认值

JavaScript函数有一个特别的地方,无论在函数定义中声明了多少形参,都可以传入任意数量的参数,也可以在定义函数时添加针对参数数量的处理逻辑,当已定义的形参无对应的传入参数时,为其指定一个默认值。

1.1 在ES5中模拟默认参数

在ES5和早期版本中,当有可选参数时,如果不显示传递,则其值默认为undefined,因此我们经常使用逻辑或操作符来为缺失的参数提供默认值。

function test(url, timeout, callback) {
    timeout = (typeof timeout !== 'undefined') ? timeout : 2000;
    callback = (typeof callback !== 'undefined') ? callback : function () { };
    //other
}

function test(url, timeout, callback) {
    timeout = (timeout !== undefined) ? timeout : 2000;
    callback = (callback !== undefined) ? callback : function () { };
    //other
}

typeof a后的类型是字符串类型,需要加“”;timeout数值类型为undefined,不需要加引号“”。

1.2 ES6中的默认参数值

ES6中简化了为形参提供默认值的过程,如果没为参数传入值,则为其提供一个初始值。

function test(url, timeout=2000, callback=function(){}) {
    //other
}

此时当不为第二、三个参数传入值,或传入undefined时,会使用其默认值。

1.3 默认参数值对arguments对象的影响

ES中,如果一个参数使用了默认参数值,无论是否显示定义了严格模式

  • arguments的长度总是必填参数的个数。
  • 实参的值始终存在arguments对象中,当传入的参数被修改时,arguments对象中的参数也不会变更。
function test(url, timeout = 2000) {
    console.log("arguments.length:" + arguments.length);//1
    console.log(arguments[0] === url);//true
    url = "aaaaaaa";
    console.log(arguments[0] === url);//false
}

1.4 默认参数表达式

在下面的例子中,如果不传入最后一个参数,就会调用getValue()函数来得到正确的默认值。

注意1:初次解析函数声明时不会调用getValue()方法,只有当调用test()且不传入第二个参数时才会调用。

注意2:当使用函数调用结果作为默认参数时,如果忘记写小括号,例如second = getValue,则最终传入的时对函数的引用,而不是函数调用的结果。

function getValue() {
    return 5;
}
function test(first, second = this.getValue()) {
    console.log("first:" + first);//1
    console.log("second:" + second);//5 
    console.log("first + second:" + (first + second));//6
}
test(1);

正因为默认参数是在函数调用时求值,所以可以使用先定义的参数作为后定义参数的默认值。例如:

function test(first, second = first) {
    console.log("first:" + first);//1
    console.log("second:" + second);//1 
}
test(1);

但先定义的参数不能访问后定义的参数。例如:

function test(first = second, second) {
    console.log("first:" + first);
    console.log("second:" + second);
}
test(undefined, 1);//抛出错误

1.5 默认参数的临时死区

定义参数时,会为每个参数创建一个新的标识符绑定,该绑定在初始化之前不可被引用,如果试图访问会导致程序抛出错误。当调用函数时

  • 20
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值