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); }; }
You should use prototypes if you wish to declare a "non-static" method of the object. var myObject = function () { }; myObject. prototype. getA = function (){ alert("A"); }; myObject.
Prototypes vs. Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.
To answer your question simply, there is no real difference. Straight from the MDN web docs definition: JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
This is exactly the situation for using prototype. I see two main benefits for doing so:
Vector3D.prototype
and assign this to Vector3DSpecial.prototype
. While you can also do this using constructors by Vector3DSpecial.prototype = new Vector3D();
, constructors may contain side-effects which will get executed in that simple prototype assignment, and therefore should be avoided. With prototypes, you may even choose only particular functions in the prototype to be copied over to the new class.Vector3D
is simply a matter of adding properties to the prototype, and allows your code to be more easily split / organised into multiple files, or to allow for adding methods in other parts of the code dynamically. Sure, you can do a combination of adding methods in the constructor and via the prototype, but that is inconsistent and is likely to lead to more complexity further down the track.When would I not use prototype? For singleton objects, for example a controller that interacts with a page and may delegate work off to other objects. A global "notification" object is one such example. Here, extending is unlikely, and the object is only created once, making the prototype an additional (conceptual) complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With