Some languages—such as Ruby, CoffeeScript and the upcoming javascript version—can declare default parameters when defining a function, like this:
The code copy is as follows:
function myFunc(param1, param2 = "second string") {
console.log(param1, param2);
}
// Outputs: "first string" and "second string"
myFunc("first string");
// Outputs: "first string" and "second string version 2"
myFunc("first string", "second string version 2");
Unfortunately, in the current JavaScript version, this writing is invalid. So what can we do to implement this way, using our existing toolset?
The easiest solution is like this:
The code copy is as follows:
function myFunc(param1, param2) {
if (param2 === undefined) {
param2 = "second string";
}
console.log(param1, param2);
}
// Outputs: "first string" and "second string version 2"
myFunc("first string", "second string version 2");
The fact is that an omitted parameter is always "undefined" when accessed. If you only have one parameter, this is a good solution, what if there were multiple ones at that time?
If you have more than one parameter, you can use an object as the parameter, which has the advantage that each parameter has a clear naming. If you pass an object parameter, you can declare the default value in the same way.
The code copy is as follows:
function myFunc(paramObject) {
var defaultParams = {
param1: "first string",
param2: "second string",
param3: "third string"
};
var finalParams = defaultParams;
// We iterate over each property of the paramObject
for (var key in paramObject) {
// If the current property wasn't inherited, proceeded
if (paramObject.hasOwnProperty(key)) {
// If the current property is defined,
// add it to finalParams
if (paramObject[key] !== undefined) {
finalParams[key] = paramObject[key];
}
}
}
console.log(finalParams.param1,
finalParams.param2,
finalParams.param3);
}
myFunc({param1: "My own string"});
This is a bit clumsy. If you use this method a lot, you can write an encapsulation function. Fortunately, many libraries now have related methods, such as the extend method in jQuery and Underscore.
The following uses the extend method of Underscore to achieve the same result above:
The code copy is as follows:
function myFunc(paramObject) {
var defaultParams = {
param1: "first string",
param2: "second string",
param3: "third string"
};
var finalParams = _.extend(defaultParams, paramObject);
console.log(finalParams.param1,
finalParams.param2,
finalParams.param3);
}
// Outputs:
// "My own string" and "second string" and "third string"
myFunc({param1: "My own string"});
This is how you can get the default parameters in the current javascript version.
Criticism and correction of inappropriate aspects in the article are welcome.