Object.assign() - weird behaviour need explanation

前端 未结 2 1798
温柔的废话
温柔的废话 2021-01-29 00:29

I\'ve got this code:



        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 00:44

    The Object.assign() function modifies the contents of the first object parameter. Thus in the first function:

    options = Object.assign(options, passedOptions); 
    

    your code works because options is the first parameter. Note that the assignment back to the options parameter has no effect, or at least no useful effect. It will assign the return value of Object.assign to the options variable, but that's the value it already has.

    The second function passes a newly-constructed empty object as the first parameter, so that means that the object passed as options won't be modified. The modified object is assigned back to options, but as it's just a function parameter that won't change the reference in the calling environment. If you wanted to do that, you'd have to return the value and assign it in the calling environment.

提交回复
热议问题