Object.assign()-奇怪的行为需要说明 [英] Object.assign() - weird behaviour need explanation

查看:153
本文介绍了Object.assign()-奇怪的行为需要说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function margeOptions(options, passedOptions) {
  options = Object.assign(options, passedOptions); 
}

let passedOpts = {a: true};
let opts = {a: false};

margeOptions(opts, passedOpts); 
console.log(opts); // as expected returns {a: true} 

但是当我稍微改变功能时,就像这样:

but when I change function a little bit, like this:

function margeOptions(options, passedOptions) {
  options = Object.assign({}, options, passedOptions); 
}

let passedOpts = {a: true};
let opts = {a: false};

margeOptions(opts, passedOpts); 
console.log(opts); // this time returns {a: false} <-- !

那这里到底发生了什么?

So what really happened in here?

推荐答案

Object.assign()函数修改第一个对象参数的内容.因此,在第一个功能中:

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

options = Object.assign(options, passedOptions); 

您的代码有效,因为 options 是第一个参数.请注意,分配回 options 参数没有任何作用,或者至少没有任何作用.它将把 Object.assign 的返回值分配给 options 变量,但这就是它已经拥有的值.

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.

第二个函数将一个新构造的空对象作为第一个参数传递,这意味着作为 options 传递的对象将不会被修改.修改后的对象被分配回 options ,但由于它只是一个函数参数,不会在调用环境中更改引用.如果要这样做,则必须返回该值并在调用环境中进行分配.

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.

这篇关于Object.assign()-奇怪的行为需要说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆