在原型上定义函数比在下面的代码中有更优雅的方法吗?理想情况下,您将在Vector函数中定义所有内容。
var Vector = function (x, y) {
this.x = x;
this.y = y;
};
Vector.prototype.plus = function (vector) {
return new Vector (this.x + vector.x, this.y + this.y);
};
Vector.prototype.minus = function (vector) {
return new Vector (this.x - vector.x, this.y - vector.y);
};
Object.defineProperty(Vector.prototype, "length", {
get: function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
});
var vt = new Vector(3, 4);
var vt2 = new Vector(5, 6);