问题描述
所以,只要我记得,我一直这样做,但我很好奇这是否真的应该做的事情。你编写一个带参数的函数,所以你预计它有一个值,但如果没有,你有充分的理由将它默认为零。我目前所做的是编写辅助函数:
So I've been doing this for as long as I can remember, but I'm curious if this is really what I should be doing. You write a function that takes a parameter, so you anticipate it to have a value, but if it doesn't, you have a good reason to default it, to say zero. What I currently do is write a helper function:
function foo() { return foo(0); };
function foo(bar) { ... };
我刚跑过一个我做过这个的实例,我奇怪地看了几秒钟之前理解我背后的逻辑。我来自php,这是微不足道的:
I just ran across an instance where I did this and I looked at it oddly for a few seconds before understanding my logic behind it. I come from php where it's trivial:
function foo(bar=0) { ... }
是否有我不知道的javascript替代方案?
Is there a javascript alternative that I'm not aware of?
推荐答案
您不能在JavaScript中使用重载函数。相反,使用基于对象的初始化,或检查值并指定默认值(如果没有提供)。
You can't have overloaded functions in JavaScript. Instead, use object based initialization, or check for the values and assign a default if none supplied.
在您的示例中,第二个函数 foo( bar)
将替换第一个。
In your example, the second function foo(bar)
will replace the first one.
这是一个使用对象初始化的函数。
Here's a function using object initialization.
function foo(config) {
extend(this, config);
}
其中 extend
是将配置对象与当前对象合并的函数。它类似于jQuery中的 $ .extend
方法,或者MooTools的 $ extend
方法。
where extend
is a function that merges the config object with the current object. It is similar to the $.extend
method in jQuery, or $extend
method of MooTools.
调用函数并传递命名键值对
Invoke the function and pass it named key value pairs
foo({ bar: 0 });
初始化的另一种方法是查看提供的值,如果值是,则指定默认值没有给出
The other way to initialize is to look at the supplied values, and assign a default if the value is not given
function foo(bar) {
bar = bar || 0;
}
只要bar不是假值,这就有效。所以 foo(false)
或 foo()
仍将初始化 bar
到 0
。对于这种情况,请进行明确检查。
This works as long as bar is not a falsy value. So foo(false)
or foo("")
will still initialize bar
to 0
. For such cases, do an explicit check.
function foo(bar) {
bar = (typeof bar == 'undefined' ? 0 : bar);
}
这篇关于功能参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!