简体   繁体   中英

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?

Javascript uses creational Prototype pattern . To make this simple, every time you call new Object() , or Object.create you are technically cloning prototype object. Object.prototype just holds reference to the prototype object.

Now why is this important? Because whatever you put on your prototype will be cloned. There is difference if you put functions on prototype, which your created/cloned objects just hold reference to, so when you change the function on prototype, it will reflect on all created object. If you specify variables though, their values will be cloned and so each object you create will have it's own values.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM