Some languages-like ruby,coffeescript and the coming JavaScript version-can declare default parameters when defining a function, as follows:
Copy Code code as follows:
function MyFunc (param1, param2 = "Second string") {
Console.log (param1, param2);
}
Outputs: "A" and "second string"
MyFunc ("A-string");
Outputs: "A" and "second string version 2"
MyFunc ("A-string", "second string version 2");
Unfortunately, in the current JavaScript version, this notation is not valid. So what can we do to implement this way, using our existing toolset?
The simplest solution is like this:
Copy Code code as follows:
function MyFunc (param1, param2) {
if (param2 = = undefined) {
Param2 = "Second string";
}
Console.log (param1, param2);
}
Outputs: "A" and "second string version 2"
MyFunc ("A-string", "second string version 2");
The fact is that an omitted parameter is always "undefined" when it is accessed. If you have only one parameter, this is a good solution, then what if there are multiple?
If you have more than one parameter, you can use an object as a parameter, so there is an advantage that each parameter has a definite name. If you pass an object parameter, you can declare the default value in the same way.
Copy Code code as follows:
function MyFunc (paramobject) {
var defaultparams = {
param1: "A-string",
param2: "Second string",
param3: "Third string"
};
var finalparams = defaultparams;
//We iterate over the "Paramobject
for" (Var key in Paramobje CT) {
//If The current property wasn ' t inherited, proceed
; if (Paramobject.hasownproperty (key)) {
/If is defined,
& nbsp; //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 way a lot of places, you can write a package function, fortunately, now a lot of libraries with related methods, such as jquery and underscore in the Extend method.
The following underscore extend methods are used to achieve the same results above:
Copy Code code as follows:
function MyFunc (paramobject) {
var defaultparams = {
PARAM1: "A-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.
The wrong place in the article is welcome to correct the criticism.