我有这样的代码:
var Vec = function(x, y) {
this.x = x || 0;
this.y = y || 0;
};
Vec.prototype = {
set: function(v) {
this.v.x = v.x;
this.v.y = v.y;
return this;
},
add: function(add) {
if (add instanceof Vec) {
return new Vec(this.v.x + add.x, this.v.y + add.y);
} else {
return new Vec(this.v.x + add, this.v.y + add);
}
}
};
这就是我创建它的方式:
var MyVector = new Vector(32, 46);
每次我要添加到MyVector时,都不必这样做;
MyVector.set(MyVector.add(new Vec(12, 7))); // MyVector = MyVector.add(new Vec(12, 7)); Same thing
我希望能够这样做:
MyVector.add(new Vec(12, 7)).set();
我如何才能做到这一点?
最佳答案
var Vec = function(a,b) {
return {
x: a,
y: b,
set: function(vector) {
this.x = vector.x;
this.y = vector.y;
},
get: function() {
return {x: this.x, y:this.y};
},
add: function(v) {
if(s.constructor === new Vec().constructor) {
values = v.get();
this.x += values.x;
this.y += values.y;
}
else {
this.x += v;
this.y += v;
}
}
}
}
现在您可以说:
var v = new Vec(12,13);
v.add(new Vect(14,15));