Search code examples
javascriptprototype

Not able to understand this prototype concept


I was going through an article` and I came across this code , where it was explaining about prototype, and how it works. What I want is , what does this sentence mean with respect to the code.

This code creates a Date object, then walks up the prototype chain, logging the prototypes. It shows us that the prototype of myDate is a Date.prototype object, and the prototype of that is Object.prototype

const myDate = new Date();
let object = myDate;

do {  
  object = Object.getPrototypeOf(object);
  console.log(object);

} while (object);

Solution

  • It’s actually quite straightforward:

    const myDate = new Date();   // Create a Date object.
    let object = myDate;
    
    do {  
      object = Object.getPrototypeOf(object); // Find the object’s prototype.
      console.log(object);                    // Print to the log.
    } while (object);            // Repeat (finding prototypes’ prototypes)
                                 // as long as there are prototypes to be found.
    

    So, we will find out that the object’s prototype also has a prototype. That’s the chain the excerpt talks about.