Tobias Springerのソリューションが好きですが、ユーティリティメソッドを使用してベクトルオブジェクトを作成することもできます。
Vector = function(x, y, z) {
this._init(x, y, z);
};
Vector.prototype = {
/**
* Fixed Constructor.
*/
constructor: Vector,
x: null,
y: null,
z: null,
/**
* Add documentation!
*/
_init: function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
},
/**
* Add documentation!
*/
add: function(otherVector) {
return new Vector(this.x + otherVector.x,
this.y + otherVector.y, this.z + otherVector.z);
},
/**
* Add documentation!
*/
scalarProduct: function(otherVector) {
return this.x * otherVector.x + this.y * otherVector.y
+ this.z * otherVector.z;
},
/**
* From Asad's answer. Returns the distance between this vector
* and <code>otherVector</code>.
* @param otherVector {Vector}
* @returns {Number}
*/
distance: function(otherVector) {
return Math.sqrt(Math.pow((this.x-otherVector.x),2)
+ Math.pow((this.y-otherVector.y),2)
+ Math.pow((this.z-otherVector.z),2));
}
// and so on....
};
したがって、次のように使用します。
var vector1 = new Vector (1, 1, 1);
var vector2 = new Vector (1, 0, 1);
var addedVector = vector1.add(vector2); // --> = (2, 1, 2)
var scalarProduct = vector1.scalarProduct(vector2); // --> = 2