咏竹莉
where there is a will,there is a way

1. 函数参数的默认值

基本用法

es6之前,不能直接为函数的参数指定默认值,只能采用变通的方法

  function log(x,y) {
      if (typeof === 'undefined') {
// 如果y有值,则为y 无值则等于 World
y = 'World'
} } log('hello') // hello world log('hello','xiaozhu') // hello xiaozhu
log('hello','') // hello

 

es6 允许为函数的参数设置默认值,即直接写在参数定义的后面

function log2(x, y = 'world') {
     console.log(x,y)
}
log2('Hello')
log2('Hello','xiaozhu')
log2('Hello','')

eg1

function point(x=0, y = 0) {
    this.x = x
    this.y = y
}
const p = new point()
console.log(p)   // {x:0, y:0}

 

参数变量是默认声明的,所以不能用letconst再次声明

function foo(x =5) {
   let x = 1;   // error
   const x = 2;  //error
}

 

与解构赋值默认值结合使用

参数默认值可以与结构赋值的默认值,结合起来使用

 

 function foo({x,y = 5}){
     console.log(x,y)
}

foo({});                // undefined  5
foo({x:1})              // 1 5
foo({x:1, y: 2})        // 1 2
foo()                  // TypeError: Cannot destructure property 'x' of 'undefined' as it is undefined. 

 

只有当函数foo的参数是一个对象时,变量x和y才会通过解构赋值生成,如果函数foo调用时没提供参数,变量x和y就不会生成,从而报错

下面是另一个结构赋值默认值的例子:

function fetch(url, {bofy= '', method = 'GET', headers = {}}) {
   console.log(method)
}
fetch('http://example.com', {});   // GET
fetch('http://example.com')        // 报错 

 

posted on 2021-06-09 10:16  咏竹莉  阅读(68)  评论(0)    收藏  举报