JavaScript defines methods for classes and objects
- 2020-03-30 04:26:04
- OfStack
This article illustrates how JavaScript defines classes and objects. Share with you for your reference. Specific methods are as follows:
In JS, classes and objects have a variety of different ways of writing, because I am not familiar with JS, so I understand to write, if a friend found wrong, please tell, learn together.
JS defines a class in two ways (I only know these two ways) :
1. How to define functions:
Definition:
function classA(a)
{
this.aaa=a; //Add a property
this.methodA=function(ppp) //Add a method
{
alert(ppp);
}
}
classA.prototype.color = "red"; //Add the properties of the object with the prototype method, which also applies to instances of the class
classA.prototype.tellColor = function() //Method to add an object with the prototype method, which also applies to instances of the class
{
return "color of "+this.name+" is "+this.color;
}
Usage:
var oClassA=new classA('This is a class example!'); //Instantiate class
var temp=oClassA.aaa; //Use the attribute aaa
oClassA.methodA(temp); // Method of use methodA
2. How to instantiate the Object class first
Definition:
var oClassA=new Object(); //The base class Object
is instantiated
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 an object using the prototype method
{
return "color of "+this.name+" is "+this.color;
}
Usage:
You can use oClassA directly, for example:
var temp=oClassA.aaa; //Use the attribute aaa
oClassA.methodA(temp); // Method of use methodA