Search code examples
javascriptprototype

Why are the properties and methods created in a function not shown in the constructor property of the prototype of that function?


function protoFunc(name) {
    this.name;
    this.getName = function () {
        return this.name;
    }
}

Here I create a constructor. Now, this constructor has a prototype property that contains an object on which you define members, i.e. methods and properties, that you want to be inherited. One of those members is the 'constructor' property, which points to the function itself.

So, why is it then that neither inside the prototype property, nor inside the constructor property, I don't see the methods and properties that I just created inside the function?

I just see this:

arguments: null
caller: null
length: 1
name: "protoFunc"
prototype:
    constructor: ƒ protoFunc(name)
    __proto__: Object
__proto__: ƒ ()

Where is the method that I just created?


Solution

  • The code you've written doesn't add anything to the prototype. Instead, it adds properties to each instance. In other words, if someone calls

    const a = new protoFunc('bob');
    

    then a will have a .name and a .getName property directly on it. It doesn't get these via the prototype chain, and they don't exist before you call new.

    If you want getName to be on the prototype chain, you need to change your code to this:

    function protoFunc(name) {
        this.name = name;
    }
    
    protoFunc.prototype.getName = function () {
        return this.name;
    }
    

    Note: i changed the line in protoFunc that said this.name to this.name = name, since that's probably what you meant to do.