From a language perspective, object-oriented programming and object-oriented JavaScript are definitely not modern things; JavaScript has been fully designed as an object-oriented language from the beginning.
Here's how to define a class or object in several ways:
1 Factory mode
The code is as follows
function createcar(iColor,iDoors,iMpg) {
varoTemCar = new Object;
oTemperCar.color = iColor;
oTemperCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor =function(){
alert(this.color) ;
};
returnoTempCar;
}
When this function is called, it creates a new object and assigns it all the necessary properties. For example
var ocar = Creatcar ("Red", 4,23);
In this method, each call to the function Createcar () creates a new function showcolor, in fact, each object shares a function, and the following example can be used to resolve the problem:
function showColor() {
alert(this.color) ;
};
functioncreatecar(iColor,iDoors,iMpg) {
varoTemCar = new Object;
oTemperCar.color = iColor;
oTemperCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor = showColor;
returnoTempCar;
}
In this way, the object is given a pointer to an existing Showcolor () function within the Createcar, which solves the problem.
2 constructor mode
function Car (iColor,iDoors,iMpg) {
this.color = iColor;
this.doors = iDoors;
this.mpg = iMpg;
this.showColor = function(){
alert(this.color) ;
}
}
Create method
var car = new Car ("Red", 4,23);
There are no objects created within the constructor, but the This keyword is used. When you call a constructor with the new operator, you first create an object when you execute the first line of code, which is accessible only with the This keyword, and then to the This property, which by default is the return value of the constructor. Like Factory mode, constructors repeat the build function, creating a separate version of the function for each function.
3 prototype mode
function Car() {
}
Car.prototype.color = "red";
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.showColor = function(){
alert(this.color);
};
Create method
var ocar = new car ();
In the secondary method, the constructor is first defined without any code. Next, you define the car's properties by adding properties to the car's prototype property. Semantically, all attributes belong to one object, which solves the problem of the previous two methods, but one disadvantage of this approach is that it is not possible to initialize the property by passing parameters to the constructor.
So let's look at the next method in conjunction with the first two methods: