Search code examples
javascriptecmascript-5

how working to Object.prototype in JavaScript


I am saw the documentation of JavaScript and I am readed about : Object.prototype and in the documentation they comment that:

The Object.prototype property represents the Object prototype object.

ok I understand tha I can create an Object of this way:

var o = new Object();

but what meaning this:

** property represents the Object prototype object**

ok I know what is Object:

The Object constructor creates an object wrapper.

my question is :

what do you mean when you say this:

The Object.prototype property represents the Object prototype object.

also while researching I saw this about prototype, this protoype term is the same to this Object.prototype?:

object that provides shared properties for other objects

here I saw that

I hope my question is bad just I am not understand this term?


Solution

  • Objects in Javascript can inherit each other. That means if we got an object child that inherits a parent object, you can access all the properties of the parent through the child:

    const parent = { age: 37 };
    const child = Object.create(parent); // child inherits parent
    console.log(child.age); // 37
    

    Now parent is called the prototype of child. Now the Object.prototype property is the upmost parent in the inheritance chain, in our case it is:

    child -> parent -> Object.prototype
    

    So every object (and nearly everything else) inherits from that property. That means that if you add something to it:

    Object.prototype.test = "hey!";
    

    All the children (everything) inherits it:

    console.log({}.test, 1..test, "test".test); // hey, hey, hey!