如何在算术表达式中编写构造函数?

Tim*_*ein 1 javascript constructor arithmetic-expressions

我想减少JavaScript中的丑陋代码,特别是与构造函数有关.

我有一个矢量定义为:

function Vector2(X, Y) {
    this.x = 0.0;
    this.y = 0.0;

    if (X)
        this.y = Y;
    if (Y)
        this.y = Y;
}
Run Code Online (Sandbox Code Playgroud)

现在,为了将两个向量加在一起,我必须写:

var vector1 = new Vector2(1.0, 0.5);
var vector2 = new Vector2(4.5, 1.0);

vector1.x += vector2.x;
vector1.y += vector2.y;
Run Code Online (Sandbox Code Playgroud)

我想让代码更漂亮,更容易阅读,并在使用许多构造函数时制作更小的文件.我想写的是:

vector1 += vector2;
Run Code Online (Sandbox Code Playgroud)

预先感谢您的任何帮助.

Den*_*ret 6

你可以这样:

function Vector(X, Y) {
    this.x = X || 0.0; // yes, I simplified a bit your constructor
    this.y = Y || 0.0;
}
Vector.prototype.add = function(v) {
   this.x += v.x;
   this.y += v.y; 
}
Run Code Online (Sandbox Code Playgroud)

你只需要这样做

var vector1 = new Vector(4,4);
var vector2 = new Vector(1,3);
vector1.add(vector2);
Run Code Online (Sandbox Code Playgroud)