[英]Webpack javascript Object.assign vs “=”
I am running a project with webpack and faced a problem. 我正在使用webpack运行一个项目,但遇到了问题。 I solved it but I want to understand how the things are working.
我解决了,但我想了解事情的进展。
I have an array with module names like [module1,module2,module3]
. 我有一个模块名称为
[module1,module2,module3]
的数组。 I use foreach
to loop this array and import every module with following syntax. 我使用
foreach
循环此数组,并使用以下语法导入每个模块。
import('./' + moduleName).then(function (promise) {
var me = promise.default(element);
})
In every module I create and return object "me" .Every module has specific functionality and parameters which aren't important for the question. 在每个模块中,我都会创建并返回对象“ me”。每个模块都有特定的功能和参数,这些功能和参数对于问题而言并不重要。
export default function (element, options) {
var me = this;
// some other code
return me;
}
The problem occurs when I have 2 some modules on one page. 当我在一页上有2个模块时,会出现问题。 The assignment me = this , somehow always create same object with same parameters even when I pass different options.
分配me = this ,即使我传递不同的选项,总会以某种方式始终创建具有相同参数的相同对象。
I solved it by changing the assignment to var me = Object.assign({},this);
我通过将赋值更改为
var me = Object.assign({},this);
来解决了var me = Object.assign({},this);
But I don't understand what is wrong with the first one. 但是我不明白第一个有什么问题。 Can you give me some explanation?
你能给我一些解释吗?
Object.assign
clones the object property. Object.assign
克隆对象属性。 but =
will copy object's reference. 但是
=
将复制对象的引用。
You can check it in below example. 您可以在以下示例中进行检查。
You can see that me
object is assigned using Object.assign
and when we change me.x
it doesn't reflect in object a
. 你可以看到,
me
对象是使用指定Object.assign
,当我们改变me.x
它不会在对象反映a
。 But in second case when we change me2.x
it updates value bx
also. 但是在第二种情况下,当我们更改
me2.x
它也会同时更新值bx
。
var a = { x: 1 }; var me = Object.assign({}, a); me.x = 2; console.log(a); console.log(me); var b = { x: 1 }; var me2 = b; me2.x = 2; console.log(b); console.log(me2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.