I'm learning classes in JS and I'm almost losing my mind with something that seems to be quite simple in OOP.
CONTEXT: I learned that creating a function with methods inserted directly into it will create an unnecessary accumulation of memory, because every time the class is instantiated each instance would have its own method occupying a different space in memory. To solve this we could access the prototype property of the function and put the methods directly there; however automatically every function has a prototype with a constructor property that points directly to the function and if I create a prototype from the outside I will overwrite the function's prototype and leave it without the constructor property, so I added this property directly to the prototype created manually.
QUESTION: my question is what is the difference of the function without the constructor property, as apparently the two codes worked similarly?
Code source: The Objective Programmer.
CODE WITH CONSTRUCTOR:
function Person (name){
this.name = name;
}
Person.prototype = {
constructor: Person,
sayName: function (){
console.log(this.name);
},
toString: function(){
return "[Person" + this.name + "]";
}
}
CODE WITHOUT CONSTRUCTOR:
function Person2 (name){
this.name = name;
}
Person2.prototype = {
sayName: function (){
console.log(this.name);
},
toString: function(){
return "[Person" + this.name + "]";
}
}