[英]Javascript constructor creating new objects with same values as previously created object
Here is my (simplified) constructor:这是我的(简化的)构造函数:
class User {
constructor() {
Object.assign(this, setup);
}
}
const setup = {
name: ''
}
export { User }
When I create a new object当我创建一个新的 object
import {
User
} from './User.js';
let user1 = new User();
user1
is what I expect. user1
是我所期望的。
If I declare user1.name = 'John'
and then create another user let user2 = new User()
then user2.name
will be John, not an empty string.如果我声明
user1.name = 'John'
然后创建另一个用户let user2 = new User()
那么user2.name
将是 John,而不是空字符串。
Can someone explain why?有人可以解释为什么吗?
It appears setup
is being changed and referenced instead of the new user object that was created.似乎正在更改和引用
setup
,而不是创建的新用户 object。
It appears
setup
is being changed and referenced instead of the new user object that was created.似乎正在更改和引用
setup
,而不是创建的新用户 object。
Yes.是的。 You need to make a copy of object before assigning it to instance of class
在将其分配给 class 实例之前,您需要复制 object
class User {
constructor() {
Object.assign(this, {...setup});
}
}
For anyone else running into similar issues, I finally figured it out.对于遇到类似问题的其他人,我终于弄清楚了。 It boils down to shallow copying versus deep copying in Javascript.
它归结为 Javascript 中的浅拷贝与深拷贝。 Both spread
(...)
and Object.assign()
perform a shallow copy while JSON methods perform a deep copy. spread
(...)
和Object.assign()
都执行浅拷贝,而 JSON 方法执行深拷贝。
If your setup is a nested object such as如果您的设置是嵌套的 object,例如
const setup = {
name: '',
address: {
city: ''
}
}
the address
object inside of setup
will remain a referenced value, not a primitive value, when {...}
or Object.assign()
is used.当使用
{...}
或Object.assign()
时, setup
内部的address
object 将保持引用值,而不是原始值。
If you want to copy the whole object, you need to copy it as JSON.parse(JSON.stringify(setup))
so my constructor should be如果要复制整个 object,则需要将其复制为
JSON.parse(JSON.stringify(setup))
所以我的构造函数应该是
class User {
constructor() {
Object.assign(this, JSON.parse(JSON.stringify(setup)));
}
}
since this performs a deep (nested) copy.因为这会执行深层(嵌套)复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.