Search code examples
javascriptoopmethodsscopeexecutioncontext

How to find the prototype object of a Class?


Learning about classes, prototypes etc. and it's finally all coming into place for me (which is quite exciting to say the least :))) However, my question has to do with finding the object prototype of a Class, where I should in theory find the its methods.

For example:

class Color {
    constructor(r, g, b, name) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.name = name;
    }
    innerRGB() {
        const { r, g, b } = this;
        return `${r}, ${g}, ${b}`;
    }
    rgb() {
        return `rgb(${this.innerRGB()})`;
    }
    rgba(a = 1.0) {
        return `rgba(${this.innerRGB()}, ${a})`;
    }
}

const red = new Color(255, 67, 89, "tomato");

Where are innerRGB(), rgb() and rgba() stored? I can't find them on the window object. Where are they? Where is the class Color stored?

When I enter Color() in the console, I get:

Uncaught TypeError: Class constructor Color cannot be invoked without 'new'

I'm clear on the inner workings of constructor functions, what's unclear to me is where the prototype resides and how I can access and inspect it.


Solution

  • Here are object relationships for your code snippet:

    enter image description here

    The object in the middle, red.__proto__, a.k.a red.constructor.prototype, a.k.a. Object.getPrototypeOf(red) a.k.a. Color.prototype is where methods are stored.

    The scope of the class Color itself (which is ƒ Color on the diagram) is its containing block, like with any other variable. In Javascript, classes are functions and functions are variables:

    {
       // block started
    
       class Color { // it's the same as "let Color = function...
          ...
       }
    
       // block ended
    
    }
    
    // "Color" doesn't exist here