Javascript 如何在算术表达式中编写构造函数?
我想减少JavaScript中丑陋的代码,特别是与构造函数相关的代码 我有一个向量定义为:Javascript 如何在算术表达式中编写构造函数?,javascript,constructor,arithmetic-expressions,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; } 现在,为了将两个向量相加,我必须写: var vector1 = new Vector2(1.0, 0.5); var vector2 = new Vec
function Vector2(X, Y) {
this.x = 0.0;
this.y = 0.0;
if (X)
this.y = Y;
if (Y)
this.y = Y;
}
现在,为了将两个向量相加,我必须写:
var vector1 = new Vector2(1.0, 0.5);
var vector2 = new Vector2(4.5, 1.0);
vector1.x += vector2.x;
vector1.y += vector2.y;
我想让代码更漂亮、更容易阅读,并且在使用许多构造函数时使文件更小。我想写的是:
vector1 += vector2;
提前感谢您的帮助。您可以:
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;
}
而你只需要这样做
var vector1 = new Vector(4,4);
var vector2 = new Vector(1,3);
vector1.add(vector2);
你可以这样做:
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;
}
而你只需要这样做
var vector1 = new Vector(4,4);
var vector2 = new Vector(1,3);
vector1.add(vector2);
我不知道您来自哪种语言,但您不能覆盖JavaScript中的运算符
我不知道您来自哪种语言,但您不能覆盖JavaScript中的运算符。这肯定实现了所有目标。我希望在重载操作符方面有更多的东西,就像在C族中一样。无论如何,非常感谢您的快速回答@dystroy。这绝对可以实现所有目标。我希望在重载操作符方面有更多的东西,就像在C族中一样。无论如何,非常感谢您的快速回答@dystroy。