JavaScript defines classes and object methods, and javascript defines objects.
This example describes how to define classes and objects in JavaScript. Share it with you for your reference. The specific method is as follows:
In JS, classes and objects are written in a variety of different ways. Because I am not familiar with JS, I will write my understanding. If any friend finds something wrong, please let me know, learn together.
JS defines two methods for a class (I only know these two methods ):
1. Define the function method:
Definition:
Copy codeThe Code is as follows: function classA ()
{
This. aaa = a; // Add an attribute
This. methodA = function (ppp) // Add a method
{
Alert (ppp );
}
}
ClassA. prototype. color = "red"; // you can use the prototype method to add object attributes. This method is also applicable to instance (object) of the class)
ClassA. prototype. tellColor = function () // use the prototype method to add an object. This method is also applicable to instance (object) of the class)
{
Return "color of" + this. name + "is" + this. color;
}
Usage:
Copy codeThe Code is as follows: var oClassA = new classA ('this is a class example! '); // Instantiate the class
Var temp = oClassA. aaa; // use the property aaa
OClassA. methodA (temp); // usage method methodA
2. First instantiate the Object class Method
Definition:
Copy codeCode: var oClassA = new Object (); // instantiate the Basic Class Object first
OClassA. aaa = 'this is a class example! '; // Add an attribute
OClassA. methodA = function (ppp) // Add a method
{
Alert (ppp );
}
OclassA. prototype. color = "red"; // use the prototype method to add Object Attributes
OclassA. prototype. tellColor = function () // Add an object using the prototype Method
{
Return "color of" + this. name + "is" + this. color;
}
Usage:
You can use oClassA directly, for example:
Copy codeCode: var temp = oClassA. aaa; // use the property aaa
OClassA. methodA (temp); // usage method methodA
I hope this article will help you design javascript programs.