ES6 参数的奇怪行为 Class

Weird behavior with parameters on a ES6 Class

我有一个 class,其中包含一个名为值的参数。这用于保存代表 canvas.

上特定形状的点的值

我需要实现一个功能,让我可以拖动这些形状,所以我需要修改形状的每个特定点,从中删除被拖动的数量。

所以我决定,当我触发我的 mousedown 事件(这是 StartMove 方法)时,我会将我的点的值保存在 startValues 变量上,并且当我四处移动鼠标时(方法 move),我然后将更新值,使用 startValues 和起点与当前鼠标位置之间的距离来确定我的新点位置。

问题是,每次我的光标移动时,this.startValues 实际上会更改以匹配 this.values,我不知道为什么 。我缺少什么简单的东西吗?

因为我将我的值存储为值,而不是坐标(帮助我在 canvas 上进行平移和缩放),我首先将值转换为位置,然后修改位置,然后将其转换回一个值。我已经包含了父 class、Grf,因此您可以看到将值更改为位置和将位置更改为值的方法。

Class有问题

class Test {
    constructor(grf){
        this.grf = grf; // Another class, which contains important methods
        this.values = []; 
        this.startValues = []; 
    }

    startMove(p0){ // p0 = [x,y]
        const {grf} = this;

        this.startValues = [...this.values]; //I also tried this.startValues = this.values
        this.p0 = p0;

        grf.canvas.addEventListener('mousemove',this.move);
        grf.canvas.addEventListener('mouseup', this.endMove);
    }

    move = (evt) => { // arrow function so 'this' is bound to Test class instead of grf.canvas
        
        const {grf, p0, values, startValues} = this;

        const coords = grf.canvas.getBoundingClientRect();
        const px = evt.clientX - coords.left;
        const py = evt.clientY - coords.top;

        for (let i = 0, iMax = this.values.length; i < iMax; i++){
            values[i][0] = grf.valX(grf.posX(startValues[0]) - (p0[0] - px));
            values[i][1] = grf.valY(grf.posY(startValues[1]) - (p0[1] - py));
        }

        console.log(this.startValues); // It changes to the same as this.values
    }

    endMove = (evt) => { // arrow function so 'this' is bound to Test class instead of grf.canvas
        const {grf} = this;
        grf.canvas.removeEventListener('mousemove',this.move);
        grf.canvas.removeEventListener('mouseup',this.endMove);
    }
}

其他class

class Grf {
    constructor(canvas){ // Not the actual constructor, just an example of what the values could look like
        this.translateX = 1000;
        this.translateY = 1000;
        this.scaleY = 10.7;
        this.scaleX = 11.2;
        this.canvas = canvas;
    }

    posX (value){
        return (value-this.translateX)*this.scaleX;
    }

    posY (value){
        return (this.canvas.height-(100*(value))-this.translateY)*this.scaleY;
    };

    valX(pos){
        return (pos/this.scaleX) + this.translateX
    }

    valY(pos){
        return (-1)*((pos/this.scaleY) + this.translateY - this.canvas.height)/100
    }

}

如何将值插入 startValuesvaluesTest class?您可能在两个数组中插入了完全相同的对象而不对其进行处理,因此两个数组都包含相同的实例。

看例子:

const obj = { a : 10 };
const a = [];
a.push(obj);
const b = [...a]; // creates new array, but with same objects
a[0].a = 20;
console.log(b[0]) // gives "{ a : 20 }" 

要使其分离,您需要复制一个对象:

a.push({...obj})