ES6中的默认参数抛出错误 [英] default parameters in ES6 throws error

查看:90
本文介绍了ES6中的默认参数抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个函数:

function add(first = second, second) { return first + second;   }

将其称为:

add(1,2); // returns 3

以上代码工作正常,但如果我们称之为:

Above code work fine but if we call it as:

add(undefined, 2); //throws error

我不知道ES6中内部参数是如何被解析的,这导致错误最后一个。

I not sure how internally parameters are parsed in ES6, which result in error for the last one.

推荐答案

第二个对于第一个进行评估,它仍然位于时间死区

second is not yet initialised when the default initialiser for first is evaluated, it's still in the temporal dead zone where accessing it will throw despite being in scope.

您应该使第二个参数可选:

You should make the second parameter optional:

 function add(first, second = first) { return first + second; }
 // and call it as
 add(2);
 add(2, undefined);

如果您真的想使第一个可选,则必须在函数体中执行:

If you really want to make the first one optional, you have to do it in the function body:

 function add(first, second) { return first + (second === undefined ? first : second); }

这篇关于ES6中的默认参数抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆