默认参数值

翻译正在进行中。

如果一个形参没有被传入对应的实参或者传入了undefined,则该形参会被赋一个默认值.

语法

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements }

描述

在JavaScript里,函数参数默认是undefined。 然而,在某些情况下设置一个不同的默认值可能是有需要的。默认参数可以帮助解决这个问题。

过去,一般的设置默认参数的方法是在函数体测试参数是否为undefined,如果是的话就设置为默认的值。下面的例子中,如果在调用multiply时,参数b的值没有提供,那么b在函数体的值就为undefined。如果直接执行a*b,函数会返回 NaN。但是第二行代码解决了这个问题,它把b的值赋为1。

function multiply(a, b) {
  b = typeof b !== 'undefined' ?  b : 1;

  return a*b;
}

multiply(5); // 5

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5

示例

Passing undefined

第二次函数调用中,即使显示的传入了undefined,color参数的值也会取默认值。

function setBackgroundColor(element, color = 'rosybrown') {
  element.style.backgroundColor = color;
}

setBackgroundColor(someDiv);            // color的值为'rosybrown'
setBackgroundColor(someDiv, undefined); // color的值为'rosybrown'
setBackgroundColor(someDiv, 'blue');    // color的值为'blue' 

Evaluated at call time

The default argument gets evaluated at call time, so unlike e.g. in Python, a new object is created each time the function is called.

function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); //[1]
append(2); //[2], not [1, 2]

This even applies to functions and variables:

function callSomething(thing = something()) { return thing }

function something(){
  return "sth";
}

callSomething();  //sth

Default parameters are available to later default parameters

Parameters already encountered are available to later default parameters:

function singularAutoPlural(singular, plural = singular+"s", 
                            rallyingCry = plural + " ATTACK!!!") {
  return [singular, plural, rallyingCry ]; 
}

//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural("Gecko");

//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural("Fox","Foxes");

//["Deer", "Deer", "Deer ... change."]
singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully
   petition the government for positive change.")

This functionality is approximated in a straight forward fashion and demonstrates how many edge case are handled.

function go() {
  return ":P"
}

function withDefaults(a, b = 5, c = b, d = go(), e = this, 
                      f = arguments, g = this.value) {
  return [a,b,c,d,e,f,g];
}
function withoutDefaults(a, b, c, d, e, f, g){
  switch(arguments.length){
    case 0:
      a
    case 1:
      b = 5
    case 2:
      c = b
    case 3:
      d = go();
    case 4:
      e = this
    case 5:
      f = arguments
    case 6:
      g = this.value;
    default:
  }
  return [a,b,c,d,e,f,g];
}

withDefaults.call({value:"=^_^="});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]


withoutDefaults.call({value:"=^_^="});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]

Functions defined inside function body

Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError (currently a TypeError in SpiderMonkey, see bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.

// Doesn't work! Throws ReferenceError.
function f(a = go()) {
  function go(){return ":P"}
}

Parameters without defaults after default parameters

Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError. This has been fixed in bug 777060 and works as expected in later versions:

function f(x=1, y) { 
  return [x, y]; 
}

f(); // [1, undefined]

Destructured parameter with default value assignment

You can use default value assignment with the destructuring assignment notation:

function f([x, y] = [1, 2], {z: z} = {z: 3}) { 
  return x + y + z; 
}

f(); // 6

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Function Definitions
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
Function Definitions
Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 49 15.0 (15.0) 未实现 未实现 未实现
Parameters without defaults after default parameters 49 26.0 (26.0) ? ? ?
Destructured parameter with default value assignment 未实现 41.0 (41.0) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) 15.0 (15.0) 未实现 未实现 未实现
Parameters without defaults after default parameters ? ? 26.0 (26.0) ? ? ?
Destructured parameter with default value assignment ? ? 41.0 (41.0) ? ? ?

相关链接

 

文档标签和贡献者

 此页面的贡献者: harryhao, lunix01, teoli, ziyunfei
 最后编辑者: harryhao,