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

查看:31
本文介绍了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天全站免登陆