Javascript adding Vectors 2D Graphics

Javascript adding Vectors 2D Graphics

本文关键字:Graphics 2D Vectors adding Javascript      更新时间:2023-09-26

我对JavaScript相当陌生,目前我真的很挣扎!我正在做一个 2D 图形模块,并且已经进行了一些需要传递矢量的测试。我被困在添加功能上。要通过测试,它说我需要:

添加函数 – 您的 Vector 对象应该有一个"添加"函数,该函数将单个 Vector 对象作为其参数。该函数应返回一个新构造的 Vector 对象,该对象是添加带有参数矢量的"this"矢量。

这是我到目前为止的代码:

 var Vector = (function () {
function Vector(pX, pY) {
    this.setX(pX);
    this.setY(pY);
}
Vector.prototype.getX = function () {
    return this.mX;
};
Vector.prototype.setX = function (pX) {
    this.mX = pX;
};
Vector.prototype.getY = function () {
    return this.mY;
};
Vector.prototype.setY = function (pY) {
    this.mY = pY;
}
 //this is my attempt at the add function
Vector.prototype.add = function (x, y) {
    var a = this.mX + x;
    var b = this.mY + y;
    return Vector(a, b);
}

return Vector;
 }());

这是它需要通过的测试:

  describe("Add", function () {
    var secondVector, thirdVector;
    secondVector = new Vector(20, 30, 0);
    thirdVector = vector.add(secondVector);
    it("X Set", function () {
        expect(thirdVector.getX()).toEqual(50);
    });
    it("Y Set", function () {
        expect(thirdVector.getY()).toEqual(70);
    });
});

抱歉,如果这令人困惑,我仍在掌握术语并理解一切的含义。如果您什么都不懂,请告诉我。

提前谢谢你。

在不给你答案的情况下,让我们分解这个问题以帮助您理解。

添加函数 – 您的 Vector 对象应该有一个"add"函数,该函数将单个 Vector 对象作为其参数。

这是说你需要创建一个名为add的函数并将其放在你的矢量对象上。您已经正确完成了此操作。但是,它接着说将单个 Vector 对象作为其参数。您当前提供两个参数:xy

// this should not provide x & y, but a previously created vector
Vector.prototype.add = function (x, y) {
// so your function definition should look something like this
// where vec is a different Vector created elsewhere.
Vector.prototype.add = function(vec) {

该函数应返回一个新构造的向量

几乎是正确的,你只是错过了new这个词.我建议您在此处阅读有关new的更多信息,因为它很重要。

矢量对象,它是使用参数 Vector 添加"this"矢量的结果。

因为您是在prototype上创建add函数,所以每当您在函数中使用this时,都意味着您正在查看调用add函数的对象实例。你在那里写的是正确的。唯一的问题是你正在添加xy参数,而不是来自另一个Vector对象的x和y。