Home>

This article details the default parameter issues in javascript,Very detailed,

Some languages--like ruby, coffeescript, and the upcoming javascript version--when defining a function,You can declare default parameters,Like this:

function myfunc (param1, param2="second string") {
 console.log (param1, param2);
}
</p>
<p>
//outputs:"first string" and "second string"
myfunc ("first string");
</p>
<p>
//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 achieve this way,Use our existing toolset?

The simplest solution is like this:

function myfunc (param1, param2) {
 if (param2 === undefined) {
 param2="second string";
 }
</p>
<p>
console.log (param1, param2);
}
</p>
<p>
//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 at that time?

If you have more than one parameter,You can use an object as a parameter,This has the advantage that each parameter is explicitly named.If you pass an object parameter,You can declare default values ​​in the same way.

function myfunc (paramobject) {
 var defaultparams={
 param1:"first string", param2:"second string", param3:"third string"
 };
</p>
<p>
var finalparams=defaultparams;
</p>
<p>
//we iterate over each property of the paramobject
 for (var key in paramobject) {
 //if the current property wasn "t inherited, proceed
 if (paramobject.hasownproperty (key)) {
 //if the current property is defined, //add it to finalparams
 if (paramobject [key]! == undefined) {
 finalparams [key]=paramobject [key];
 }
 }
 }
</p>
<p>
console.log (finalparams.param1, finalparams.param2, finalparams.param3);
}
myfunc ({param1:"my own string"});

This is a bit awkward,If you use this method a lot,Can write a wrapper function,Fortunately,A lot of libraries now have related methods,For example, the extend method in jquery and underscore.

Below uses the extend method of underscore to achieve the same result as above:

function myfunc (paramobject) {
 var defaultparams={
 param1:"first string", param2:"second string", param3:"third string"
 };
</p>
<p>
var finalparams=_.extend (defaultparams, paramobject);
</p>
<p>
console.log (finalparams.param1, finalparams.param2, finalparams.param3);
}
</p>
<p>
//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.

  • Previous C # implements calculation of birthday characters
  • Next Two methods to achieve IE browser compatible placeholder effect based on jQuery