If you have read my last blog on prototypes, you will know that you could use functions as a machine to create objects. Such functions that create objects are called constructor functions. Now let's say you have an object 'objJustLikeYou', and you want one more (or may be few more) object(s) like 'objJustLikeYou'. You do not want to clone it as that will simply give you a copy of the object as it exists in the current state. You do not want that but an object like objJustLikeYou in the original state. A copy will give you objJustLikeYou with properties that may be in a different state (current state of objJustLikeYou) than the original state when objJustLikeYou was freshly created.
In other words, when objJustLikeYou was created, it had the property say 'x' in a sate x=0, but now the state is x=100. So, if you opt to make a copy of objJustLikeYou, your new object objJustLikeYou2 will also have the state x=100 which is not your objective. Your objective is to get an object like objJustLikeYou but in the original state irrespective of what state the objJustLikeYou is in.
In summary, you want to get hold of the constructor function that created objJustLikeYou and get it to make one or more fresh objects for you. The trouble is you have no access to its constructor function, or do you!
This is where you could use the constructor property of your object objJustLikeYou. See the code below:
Now that you have the constructor function, you could have all the fun you want with it. Let's create an object out of it now.
You could create n number of such objects from the constructor function.
A very important point to note here is that the property "constructor" comes from the prototype of the constructor function of objJustLikeYou. So, when you say objJustLikeYou.constructor, it doesn't come from objJustLikeYou but from the prototype of its constructor.
objJustLikeYou (no constructor property) -- Constructor Function -- Prototype (has constructor property)
Wonder what will be the constructor function of the object below?
Give it a shot and find out!



This object is internally created by Object constructor function
ReplyDeleteTrue that! :)
ReplyDeleteFor Every object if prototype is not explicitly defined then its default prototype is Object so it will return Object constructor function
ReplyDeleteis obj.constructor function make new obj inside the variable object?
ReplyDelete