Using constructor and prototype together, you can create objects just like using other programming languages. This concept is very simple, that is, using constructors to define all non-function attributes of an object and using prototype to define the function attributes (methods) of an object ). Result All functions are created only once, and each object has its own object attribute instance.
Code
// Mixed constructor/prototype
Function car (scolor, idoors, impg ){
This. Color = scolor;
This. Doors = idoors;
This. mpg = impg;
This. Drivers = new array ("Mike", "Sue ");
}
Car. Prototype. showcolor = function (){
Alert (this. Color );
}
VaR ocar1 = new car ("red", 4,23 );
VaR ocar2 = new car ("blue", 3,33 );
Ocar1.drivers. Push ("Matt ");
Ocar1.drivers (); // output Mike, Sue, Matt
Ocar2.drivers (); // output Mike, Sue
Now it is more like creating a common object. All non-function attributes are created in the constructor, which means that the default values of the attributes can be assigned to the constructor parameters. Because only one instance of the showcolor () function is created, there is no memory waste. In addition, adding the "Matt" value to the drivers array of ocar1 does not affect the ocar2 array. Therefore, when outputting the values of these arrays, ocar1.drivers displays "Mike, Sue, Matt ", ocar2.drivers displays "Mike, Sue ".