JS 不可变对象保持相同的对象类型
JS immutable objects keep the same object type
假设我有一个 class。
class Test {
constructor() {
this.name = 'name';
this.arr = [];
}
}
我需要从这个class创建多个实例。
const entities = {
1: new Test(),
2: new Test()
}
现在,我需要以浅克隆方式更新其中一个属性。
const newEntities = {
...entities,
[1]: {
...entities[1],
name: 'changed'
}
}
console.log(newEntities[1].arr === entities[1].arr) <=== true
这是可行的,但问题是 [1]
是一个简单的对象,不再是 Test
的实例。
我该如何解决?
您可以在 [1]
对象上使用 Object.setPrototypeOf。
因此,它将是:
Object.setPrototypeOf(newEntities[1], Test.prototype);
您无法使用对象解构来保留实例,因此您需要实现此行为。
第一个例子,在构造函数中设置新属性:
class Test {
constructor(props) {
props = props == null ? {} : props;
this.name = 'name';
this.arr = [];
Object.assign(this, props);
}
}
const newEntities = {
...entities,
[1]: new Test({ ...entities[1], name: 'changed' })
}
Sencod示例,使用自定义方法:
class Test {
constructor() {
this.name = 'name';
this.arr = [];
}
assign(props) {
props = props == null ? {} : props;
const instance = new Test();
Object.assign(instance, this, props);
return instance;
}
}
const newEntities = {
...entities,
[1]: entities[1].assign({ name: 'changed' })
}
假设我有一个 class。
class Test {
constructor() {
this.name = 'name';
this.arr = [];
}
}
我需要从这个class创建多个实例。
const entities = {
1: new Test(),
2: new Test()
}
现在,我需要以浅克隆方式更新其中一个属性。
const newEntities = {
...entities,
[1]: {
...entities[1],
name: 'changed'
}
}
console.log(newEntities[1].arr === entities[1].arr) <=== true
这是可行的,但问题是 [1]
是一个简单的对象,不再是 Test
的实例。
我该如何解决?
您可以在 [1]
对象上使用 Object.setPrototypeOf。
因此,它将是:
Object.setPrototypeOf(newEntities[1], Test.prototype);
您无法使用对象解构来保留实例,因此您需要实现此行为。
第一个例子,在构造函数中设置新属性:
class Test {
constructor(props) {
props = props == null ? {} : props;
this.name = 'name';
this.arr = [];
Object.assign(this, props);
}
}
const newEntities = {
...entities,
[1]: new Test({ ...entities[1], name: 'changed' })
}
Sencod示例,使用自定义方法:
class Test {
constructor() {
this.name = 'name';
this.arr = [];
}
assign(props) {
props = props == null ? {} : props;
const instance = new Test();
Object.assign(instance, this, props);
return instance;
}
}
const newEntities = {
...entities,
[1]: entities[1].assign({ name: 'changed' })
}