There are several ways to build a class in javascript:
1.Factory Mode
Copy Code code as follows:
function Createcar () {
var car = new Object ();
Car.color= "B";
car.length=1;
Car.run=function () {alert ("Run");}
return car;
}
Once you have defined such a function, you can use:
var car1 = Createcar ();
var car2 = Createcar ();
To create a new object, the problem is that every time you create a car object, the run function must be re-created once. Wasting memory
2.Constructor Mode
Copy Code code as follows:
function car () {
This.color= "B";
this.length=1;
This.run=function () {alert ("Run");}
}
var car1=new car ();
var car2=new car ();
This is the most basic way, but it has the same problems as the factory way.
3.prototype Mode
Copy Code code as follows:
function car () {
}
Car.prototype.color= "B";
car.prototype.length=1;
Car.prototype.run=function () {alert ("Run");
}
The disadvantage of this approach is that when this class has a reference property, changing the property of an object also changes the properties of the other object.
Like what:
Copy Code code as follows:
Car.prototype.data1=new Array ();
var car1=new car ();
var car2=new car ();
Car1.data1.push ("a");
At this point, Car2.data also contains the "a" element
4.prototype/constructor Hybrid MethodCommon
Copy Code code as follows:
function car () {
This.color= "B";
this.length=1;
This.data1=new Array ();
}
Car.prototype.run=function () {
Alert ("dddd");
}
This way to go beyond those shortcomings. is currently a wide range of ways to use
5. Dynamic prototype method [commonly used]
Copy Code code as follows:
function car () {
This.color= "B";
this.length=1;
This.data1=new Array ();
if (typeof car.initilize== "undefined") {
Car.prototype.run=function () {alert ("a");}
}
Car.initilize=true;
}
In these ways, the most commonly used is the hybrid Prototype/constructor and dynamic prototype mode.