There are multiple methods to define classes or objects in javascript:
Create a car as an instance.
VaR ocar = new object;
Ocar. color = "red ";
Ocar. Doors = 4;
Ocar. mpg = 23;
Ocar. showcolor = function ()
{
Alert (this. Color );
}
- Factory construction, for example:
Function createcar (scolor, idoors, impg)
{
VaR otempcar = new object;
Otempcar. Color = scolor;
Otempcar. Doors = idoors;
Otempcar. mpg = impg;
Otempcar. showcolor = function ()
{
Al (this. color)
}
Return otempcar;
}
Disadvantage: each object has its own showcolor function.
Function car (scolor, idoors, impg)
{
This. Color = scolor;
This. Doors = I;
This. mpg = impg;
This. showcolor = function ()
{
Alert (this. color)
};
}
Disadvantages: the constructor repeatedly generates a function. You can use an external function to rewrite the constructor (not quite familiar );
- Prototype: The prototype attribute is used.
Function car ()
{
}
Car. Prototype. color = "red ";
Car. Prototype. Doors = 4;
Car. Prototype. mpg = 23;
Car. Prototype. Drivers = new array ("Mike", "Sue ");
Car. Prototype. showcolor = function ()
{
Alert (this. Color );
}
Disadvantage: add drivers to one instance and add another instance.
- Hybrid constructor and prototype
Function car ()
{
}
Car. Prototype. color = "red ";
Car. Prototype. Doors = 4;
Car. Prototype. mpg = 23;
Car. Prototype. Drivers = new array ("Mike", "Sue ");
Car. Prototype. showcolor = function ()
{
Alert (this. Color );
}
Two drawbacks are solved.
- Dynamic Prototype Construction
Function car (scolor, idoors, impg)
{
This. Color = scolor;
This. Doors = idoors;
This. mpg = impg;
This. Drivers = new array ("Mike", "Sue ");
If (typeof car. _ initialized = "undefined ")
{
Car. Prototype. showcolor = function ()
{
Alert (this. color)
}
Car. _ initialized = true;
}
}
Function car ()
{
VaR otempcar = new object;
Otempcar. color = "red ";
Otempcar. Doors = 4;
Otempcar. mpg = 23;
Otempcar. showcolor = function ()
{
ALE (this. color)
}
Return otempcar;
}
Which method is used:
Currently, constructors and prototypes are popular, and dynamic prototypes are also popular.