Most guides on JavaScript explain object creation using constructor functions as follows:
let Person = function (fn, ln) {
this.fn = fn;
this.ln = ln;
};
Person.prototype.greet = function () {
console.log("hello "+ this.fn+ " "+ this.ln)
};
That is: fields are defined in the constructor function while methods are added to the prototype.
Now I understand that the properties defined inside the constructor function will form N copies for N instances, while those on the prototype will have 1 copy shared among all N instances. So it makes sense that properties are defined inside the constructor, as we obviously don't want the copies to be sharing mutable properties like arrays etc.
What I don't get is why the methods aren't defined in the constructor function too. Like this:
let Person = function (fn, ln) {
this.fn = fn;
this.ln = ln;
this.greet = function () {
console.log("hello "+ this.fn+ " "+ this.ln)
};
};
I understand that it will result in there being a copy for each instance and the methods belonging to the object itself rather than its parent/prototype, but is there any particular downside to it?
It just seems a lot more coherent and similar to Ruby etc. style-wise.