ES6 object destructuring with a default value assignment

前端 未结 2 1738
青春惊慌失措
青春惊慌失措 2021-01-28 17:16

Consider the following code:

const log = ({a,b=a}) => console.log(a,b);
log({a:\'a\'})

The variable b is assigned the value

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-28 17:56

    Am I allowed to do this kind of default value assignment in a destructured object?

    Yes. The destructuring expression is evaluated from left to right, and you can use variables that are already initialised from properties in the default initialiser expressions of later properties.

    Remember that it desugars to

    const log = (o) => {
      var a = o.a;
      var b = o.b !== undefined ? o.b : a;
    //                                  ^ a is usable here
      console.log(a,b);
    };
    

提交回复
热议问题