The examples in this article describe how JavaScript defines classes and objects. Share it with everyone for your reference. The specific method is as follows:
In JS, there are many different ways to write classes and objects. Since I am not very familiar with JS, I write based on my understanding. If any friend finds something wrong, please tell me and we can learn together.
There are two ways to define a class in JS (I only know these two):
1. How to define functions:
Definition:
function classA(a)
{
This.aaa=a; //Add an attribute
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 instances (objects) of the class
classA.prototype.tellColor = function() //Method to add objects using prototype method. This method also applies to instances (objects) of classes
{
return "color of " this.name " is " this.color;
}
How to use:
var oClassA=new classA('This is a class example!') ; //Instantiation class
var temp=oClassA.aaa; //Use attribute aaa
oClassA.methodA(temp); //Use method methodA
2. How to instantiate the Object class first
Definition:
var oClassA=new Object(); //Instantiate the base class first Object
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 attributes of the object
oclassA.prototype.tellColor = function() //Method to add objects using prototype method
{
return "color of " this.name " is " this.color;
}
How to use:
You can use oClassA directly, such as:
var temp=oClassA.aaa; //Use attribute aaa
oClassA.methodA(temp); //Use method methodA
I hope this article will be helpful to everyone’s JavaScript programming design.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn