Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - Default value for function parameter?

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) { ... };

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) { ... }

Is there a javascript alternative that I'm not aware of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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);
}

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;
}

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...