This article describes the method of defining classes and objects in JavaScript. Share it for your reference. The specific methods are as follows:
In JS, there are many different ways to write classes and objects. Because I am not very familiar with JS, I write based on my understanding. If any friend finds something wrong, please tell me and learn together.
There are two ways to define a class in JS (I only know these two):
1. How to define functions:
definition:
The code copy is as follows: function classA(a)
{
this.aaa=a; //Add a property
this.methodA=function(ppp) //Add a method
{
alert(ppp);
}
}
classA.prototype.color = "red"; //Use the prototype method to add the attributes of the object. This method is also applicable to the instance of the class (object)
classA.prototype.tellColor = function() //A method to add object using the prototype method. This method is also applicable to class instances (objects)
{
return "color of "+this.name+" is "+this.color;
}
How to use:
Copy the code as follows: var oClassA=new classA('This is a class example!'); //Instantiate the class
var temp=oClassA.aaa; //Use attribute aaa
oClassA.methodA(temp); //Usage method methodA
2. The way to instantiate the Object class first
definition:
Copy the code as follows: var oClassA=new Object(); //Instantiate the basic class Object first
oClassA.aaa='This is a class example!'; //Add a property
oClassA.methodA=function(ppp) //Add a method
{
alert(ppp);
}
oclassA.prototype.color = "red"; //Use the prototype method to add the properties of the object
oclassA.prototype.tellColor = function() // Method to add objects using the prototype method
{
return "color of "+this.name+" is "+this.color;
}
How to use:
You can use oClassA directly, such as:
Copy the code as follows: var temp=oClassA.aaa; //Use attribute aaa
oClassA.methodA(temp); //Usage method methodA
I hope this article will be helpful to everyone's JavaScript programming.