“A prototype is an object of any type which is used to construct future copies of it.”
EXAMPLE:
Just like cars in a factory. First engineers design and construct a prototype and, when done, its manufactured in series.
Prototypal inheritance:
“In most languages, there are classes and objects. Classes inherit from other classes.”
Program:
Var animal= {
Walk: function ()
{
Console.log (‘walking…’);
};
Eat:
Function ()
{
Console.log (‘eating…’);
}
};
Var person=function ()
{
This. Talk=function ()
{
Console.log (‘hello…’);
};
};
Person. Prototype=animal;
…
Person. Prototype=animal;
Var David=new person ();
//now we can do…
David .talk ();//hello!;
//but we can also do…
David.eat ();//eating…
David. Walk (); //walking…
But if we look inside the newly created “david” object; you’ll can see there are not “eat” and “walk” methods.
How it is doing:
By using prototype chain
Console.dir (David);
{
Talk: function () {…}
-Proto-:
{
Walk: function () {…}
Eat: function () {…}
-Proto-: object
}
}
When you call a function or access a member, javascript looks into the first level of the prototype chain; if it doesn’t exist it looks into the second level, then third…and so on.
It stops looking when fixed a null-proto- property in our example,
Prototype chain:
Searching for a member in the prototype chain.
Exist “eat” function in David second level?
Exist “eat” function in David’s 1st level?
David eat () No
End
Yes yes
.
A prototype is an internal object from which other objects inherit properties. Its main purpose is to allow multiple instances of an object to share a common property. Thus, object properties which are defined using the prototype object are inherited by all instances which reference it.
0 comments:
Post a Comment