博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
默认参数如何在JavaScript ES6中工作
阅读量:2522 次
发布时间:2019-05-11

本文共 5130 字,大约阅读时间需要 17 分钟。

With Default Parameters, you can set default values for any arguments. Then when a function is invoked and those arguments aren’t defined, your default values will stand in for them.

使用默认参数,可以为任何参数设置默认值。 然后,当调用一个函数并且未定义这些参数时,您的默认值将代替它们。

In this article, I’ll show you how to use Default Parameters to make certain arguments required.

在本文中,我将向您展示如何使用默认参数来使某些参数成为必需。

I’ve also recorded a 7-minute video version of this article:

我还记录了这篇文章的7分钟视频版本:

Below we have a function called calculatePayment. This function will take in three arguments: price, salesTax, and a discount. The goal of this function is to take in those three items and return a final price, after taking into consideration the sales tax and any discount.

在下面,我们有一个称为calculatePayment的函数。 此函数将接受三个参数: pricesalesTaxdiscount 。 此功能的目的是考虑到营业税和任何折扣后,将这三项物品纳入进账并返回最终价格。

What’s interesting about this function is the only argument that is really required is the price. When we define calculatePayment, we should set default values for both salesTax and discount so if they’re not specified when the function is invoked, they’ll still be initialized with those values.

此函数有趣的是,真正需要的唯一参数是price 。 当我们定义calculatePayment ,我们应该为salesTaxdiscount设置默认值,因此,如果在调用函数时未指定默认值,则仍将使用这些值进行初始化。

With ES5, we’d typically do that like this:

使用ES5,我们通常会这样做:

function calculatePayment (price, salesTax, discount) {   salesTax = salesTax || 0.047   discount = discount || 0
// math}

If you’ve never seen the || operator used like this before, here’s what’s going on. When calculatePayment is invoked, salesTax is going to be set to salesTax is, unless it was falsy, then it will be set to 0.047. The same thing is happening for discount.

如果您从未见过|| 以前使用过这样的运算符,这是怎么回事。 当calculatePayment被调用时, salesTax将被设置为salesTax ,除非它是falsy,那么它将被设置为0.047discount也发生了同样的事情。

If you’re observant, you may have noticed some issues with the current implementation. What happens if when we invoke calculatePayment passing in 100, 0, and 0?

如果您观察的话,可能已经注意到当前实现的一些问题。 会发生什么,如果当我们调用calculatePayment传递1000 ,和0

calculatePayment(100,0,0)

You might expect both salesTax and discount to be set to 0 since that’s what we specified when the function was invoked. However, in JavaScript, 0 is falsy. So instead of salesTax being 0 as we specified, it’s instead set to our default value of 0.047. To fix this, we can use the typeof operator rather than relying on the || operator.

您可能希望将salesTaxdiscount都设置为0因为这是我们在调用函数时指定的值。 但是,在JavaScript中, 0为假。 因此,代替我们指定的salesTax0 ,而是将其设置为默认值0.047 。 为了解决这个问题,我们可以使用typeof运算符,而不是依靠|| 操作员。

function calculatePayment (price, salesTax, discount) {    salesTax = typeof salesTax === 'undefined' ? 0.047 : salesTax  discount = typeof discount === 'undefined' ? 0 : discount
// math}

Much better. Now, salesTax will be 0 just as we’d expect. If you’re still with me, you’re in a great place to now understand the value add of ES6’s Default Paremeters since they solve the same problem. However, instead of using the typeof operator to check if the values are undefined, we can do something like this instead,

好多了。 现在, salesTax将为0 ,正如我们期望的那样。 如果您仍然与我在一起,那么您现在就可以了解ES6的默认Paremeter的增值之处,因为它们可以解决相同的问题。 但是,我们可以使用类似的方法来代替使用typeof运算符检查值是否未定义,

function calculatePayment(price, salesTax = 0.047, discount = 0) {   console.log('tax', salesTax)    console.log('discount', discount)
// math}

Notice all we did was move the logic up into where we define the function’s parameters. Much cleaner.

注意,我们所做的只是将逻辑上移到定义函数参数的位置。 清洁得多。

Now typically this is where posts about Default Parameters end. However, I think there’s one more cool|weird|clever aspect of Default Parameters that’s worth mentioning.

现在通常是有关“默认参数”的帖子结束的地方。 但是,我认为还有一个很酷的默认参数方面值得一提。

Looking back at the calculatePayment function, I mentioned the only real required argument to the function was the price. Everything else we could just set a default value for but if price wasn’t passed in, the function would break. What if there was a way, using default parameters, to have our function throw an error if price was undefined when the function was invoked? As you can probably guess, there is.

回顾一下calculatePayment函数,我提到了该函数唯一真正需要的参数是price 。 其他所有操作我们都可以为其设置默认值,但是如果未传递price ,该函数将中断。 如果在调用函数时undefined price情况下使用默认参数让我们的函数抛出错误怎么办? 您可能会猜到。

First, let’s create a function called isRequired who’s whole purpose is to just throw an error.

首先,让我们创建一个名为isRequired的函数,其目的只是抛出一个错误。

function isRequired (name) {   throw new Error(name + 'is required') }

Now, similar to what we did earlier with salesTax and discount, let’s set price equal to the function invocation of our isRequired function inside of the calculatePayment’s parameters.

现在,类似于我们早期做salesTaxdiscount ,让我们设置price等于我们的函数调用isRequired的功能里面calculatePayment的参数。

function isRequired (name) {   throw new Error(name + 'is required') }
function calculatePayment(   price = isRequired('price'),   salesTax = 0.047,   discount = 0 ) {       // math
}

Now if we invoke calculatePayment and don’t pass in a price, we’ll get an error.

现在,如果我们调用calculatePayment并且不传递price ,我们将得到一个错误。

Thanks for reading! I originally published this on as part of my “” course.

谢谢阅读! 我最初将此内容发布在作为“ ”课程的一部分。

翻译自:

转载地址:http://fnwzd.baihongyu.com/

你可能感兴趣的文章
词法分析程序
查看>>
Java反射
查看>>
[ACM_模拟][ACM_数学] LA 2995 Image Is Everything [由6个视图计算立方体最大体积]
查看>>
1040 有几个PAT
查看>>
BZOJ 1412 [ZJOI2009]狼和羊的故事 | 网络流
查看>>
原型模式
查看>>
Hadoop RPC源码阅读-交互协议
查看>>
WASAPI、DirectSound/DS、WaveOut、Kernel Streaming/KS
查看>>
Perl按行分割文件
查看>>
根据现有表操作基于active record的model
查看>>
NotMapped属性特性
查看>>
Count and Say
查看>>
GridView数据导入Excel/Excel数据读入GridView
查看>>
566. Reshape the Matrix
查看>>
python数据结构与算法之搜索
查看>>
(最小点覆盖) poj 2226
查看>>
(树形DP) poj 3659
查看>>
获取类的属性名和值
查看>>
python对json的操作总结
查看>>
学习进度表第十一周
查看>>