Sergey Ilinsky wrote:
What is the principle difference between declaring methods/properties
in the constructor function body and via prototypes.
There is one prototype object shared by the instances created with one
constructor function thus if you want a "class" of objects then it makes
sense to at least put all methods on the prototype as that is far more
efficient and far more meaningful, a method defines the dynamic
behaviour of an object and is usually expected to be consistent for all
instances in a "class". Thus methods should be created by adding a
function property to the prototype e.g.
function God (name) {
this.name = name;
}
God.prototype.praise = function () {
alert('All hail ' + this.name);
};
Now all instances e.g.
var god1 = new God('Kibo');
var god2 = new God('Xibo');
do not have their own function property named praise but share one via
the prototype and that is the proper way if all instances are supposed
to have the same behaviour.
And if you did
function God (name) {
this.name = name;
this.praise = function () {
alert('All hail ' + this.name);
}
}
then each instance created with new God('someName') would have its own
function property named praise but as the body is identical you would
just waste storage space then.
So having
function SomeConstructorFunction (args) {
...
}
SomeConstructorFunction.prototype.methodName = function (...) {
...
};
is just JavaScript's operational way to declare a common method for a
"class" of objects.
For normal non function properties it is different, usually in object
oriented development those properties make up the data of the object
instance which make it unique so there it usually doesn't make sense to
have a property on the prototype, unless for instance you wanted to have
a default value for a property.
--
Martin Honnen
http://JavaScript.FAQTs.com/