For example, the foo function has a default output that overwrites the same property if it passes an obj argument

The first way to write it

Var obj1 = {name:"zhangsan", age:19} function foo(obj){var obj1 = {name:"zhangsan", age:19} Var newObj = {... obj1, ... obj } console.log(newObj.name,newObj.age) } foo()//zhangsan 19 foo(obj)//zhangsan 23Copy the code

Let’s see if there’s an easier way to write it

function foo(obj={
        name:"zhangsan",
        age:19
    }){
    console.log(obj.name,obj.age)
}
foo()//zhangsan 19
foo(obj)//undefined 23
Copy the code

Passing a default object to a parameter does satisfy the requirement without passing a parameter, but passing an incomplete object does not satisfy the requirement without passing an attribute as undefined

A better solution:

function foo({
        name="zhangsan",
        age=19
    }={}){
    console.log(name,age)
}
Copy the code

{name=”zhangsan”,age=19}={}, use the method of parameter deconstruction, the first {} to deconstruct the attributes of the object, and give the default value; If foo does not pass an argument (foo()), an error will be reported, so we need to give a default value for an empty object as a whole. If foo does not pass an argument, we will pass an empty object by default.