es6 assign default values used in conjunction deconstruction

The default parameter values ​​can be assigned default values ​​and deconstruction, in combination.

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 read property 'x' of undefined 

The above code uses the default value assignment deconstruction object only, not using the default values of function parameters. Only when the function fooparameter is an object, variable x, and ywill generate an assignment by deconstruction. If the function foois not provided when the call parameters, variables x, and ywill not be generated, and thus an error. The default value provided by the function parameters, you can avoid this situation.

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

Guess you like

Origin www.cnblogs.com/xiaoxiaoxun/p/12157672.html