0

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 + "]";
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Benize
  • 44
  • 6

1 Answers1

0

A seen on this section of the MDN docs on this topic, there won't be a difference here, as you're not technically changing the constructor on either object.

Where this would matter, however, is if you changed the constructor of the function. Take the following code snippet from the aforementioned MDN page:

function Parent() { /* ... */ }
Parent.prototype.parentMethod = function parentMethod() {}

function Child() {
   Parent.call(this) // Make sure everything is initialized properly
}
Child.prototype = Object.create(Parent.prototype) // re-define child prototype to Parent prototype

Child.prototype.constructor = Child // return original constructor to Child

The important part of this figure is that at the end, you can see the Child.prototype.constructor is set BACK to it's original constructor, just like you're doing in your example with the Person function.

Mytch
  • 380
  • 1
  • 3
  • 16
  • "*you're only setting it to be what it already is going to be by default*" - no, in the OPs second snippet it defaults to `Object` (inherited from `Object.prototype.constructor`) – Bergi May 22 '22 at 00:14