There are several ways to build a class in Javascript:
1.Factory method
function createCar(){
var car = new Object();
car.color="b";
car.length=1;
car.run=function(){alert(”run”);}
return car;
}
After defining such a function, you can use:
var car1 = createCar();
var car2 = createCar();
to create a new object. The problem with this method is that every time a car object is created, the run Function must be re-created. It is a waste of memory.
2.Constructor method
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 method, but it also has the same problems as the factory method
3.prototype method
function Car(){
}
Car.prototype.color=”b”;
Car.prototype.length=1;
Car.prototype.run=function(){alert ("run");
}
The disadvantage of this method is that when this class has a reference attribute, changing this attribute of one object will also change the attributes of other objects
For example:
Car.prototype.data1=new Array() ;
var car1=new Car();
var car2=new Car();
car1.data1.push("a");
At this time, car2 .data also contains the "a" element
4. Prototype/Constructor hybrid method [Commonly used]
function Car(){
this.color=”b”;
this.length=1;
this .data1=new Array();
}
Car.prototype.run=function(){
alert("dddd");
}
This kind This method eliminates those shortcomings. It is currently a widely used method
5. Dynamic prototype method [commonly used]
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;
}
Among these methods, the most commonly used are hybrid prototype/constructor and dynamic prototype methods