我正在尝试运行此代码,并能够在“内存”数组中“保存”一个对象,以查看同一对象更改后具有的过去属性。
这是课程:
class Circle {
radius;
center = {};
memory = [];
constructor(radius, x, y) {
this.radius = radius;
this.center.x = x;
this.center.y = y;
moveX(steps) {
if (!isNaN(steps)) {
this.saveMemory(this);
this.center.x += steps;
}
return this.center.x;
}
saveMemory(circle) {
let temp = (({ memory, ...rest }) => rest)(circle);
this.memory.push(temp);
}
当我查看内存数组时,它显示对象之后 x的变化。
var circle1 = new Circle(5, 1, 1);
circle1.moveX(2); // memory = [{radius:5,center{x:3,y:1})
如何进行更改之前保存对象?
仅克隆对象
var circle1 = new Circle(5, 1, 1);
var circlecopy = Object.assign({}, circle1)
circle1.moveX(2); // memory = [{radius:5,center{x:3,y:1})
您也可以只散布对象而不是Object.assign()
{...circle1}