I'm creating a Vector class, which can basically hold three numerical values. However, a lot of operations can be done on such a vector - e.g. getting the magnitude, adding or subtracting another vector etc.
I was wondering whether these functions should be coded as being a prototype function of the Vector class, or that I should define them in the constructor.
So which of these two methods is preferable?
function Vector3D(x, y, z) {
this.x = x;
this.y = y
this.z = z;
}
Vector3D.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
or
function Vector3D(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…