类字段丢失值

时间:2020-11-09 20:41:01

标签: javascript jquery-ui

我正在尝试在不同坐标坐标空间(笛卡尔坐标系,相对于页面和极坐标)中的点之间进行转换。我有所有这些的类,并且我试图通过在构造函数中将它们彼此传递来转换它们。我遇到了一个实际坐标域丢失的问题。

@PropertySource

当我尝试在jQuery-ui draggable.start回调中进行转换时,就会出现此问题。

class CartesianPoint {
    constructor(a, b) {
        if (a instanceof PagePoint) {
            this.SetFromPage(a);
        }
        else if (a instanceof PolarPoint) {
            this.SetFromPolar(a);
        }
        else {
            this.x = a;
            this.y = b;
        }
        this.SetFromPage = this.SetFromPage.bind(this);
        this.SetFromPolar = this.SetFromPolar.bind(this);
    }

    SetFromPage(pt) {
        this.x = pt.left;
        this.y = -pt.top;
    }

    SetFromPolar(pt) {
        this.x = pt.radius * Math.cos(pt.angle);
        this.y = pt.radius * Math.sin(pt.angle);
    }
}

class PagePoint {
    constructor(a, b) {
        if (a instanceof PolarPoint) {
            this.SetFromPolar(a);
        }
        else if (a instanceof CartesianPoint) {
            this.SetFromCartesian(a);
        }
        else {
            this.left = a;
            this.top = b;
        }
        this.SetFromPolar = this.SetFromPolar.bind(this);
        this.SetFromCartesian = this.SetFromCartesian.bind(this);
    }

    SetFromPolar(pt) {
        let cart = new CartesianPoint(pt);
        this.SetFromCartesian(cart);
    }

    SetFromCartesian(pt) {
        this.left = pt.x * 1;
        this.top = -pt.y * 1;
    }
}

如果我登录pt1,这就是我在Chrome检查器中看到的内容:

enter image description here

pt2看起来完全符合我的预期:

enter image description here

如果您在SetFromPage()中设置了pt1.x和pt1.y之后立即调用它们,则它们将填充正确的值,但是稍后从另一个范围调用时,它们将返回NaN。

1 个答案:

答案 0 :(得分:0)

我不清楚为什么会发生这种情况,但我通过这样重写这些类来解决了这个问题:

function CartesianPoint(a, b) {
    if (a.PointType === PointType.Page) {
        return CartesianPoint(a.left, -a.top);
    }
    else if (a.PointType === PointType.Polar) {
        return CartesianPoint(a.radius * Math.cos(a.angle), a.radius * Math.sin(a.angle));
    }
    else {
        let pt = {
            x: a,
            y: b,
            PointType: PointType.Cartesian
        };
        Object.freeze(pt); //this line appears to be what fixed it
        return pt;
    }
}

这意味着它在此过程中某处正在失去其范围。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

相关问题