Home > Web Front-end > JS Tutorial > JavaScript methods for defining classes and objects_javascript tips

JavaScript methods for defining classes and objects_javascript tips

WBOY
Release: 2016-05-16 16:30:04
Original
1488 people have browsed it

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:

Copy code The code is as follows:
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:
Copy code The code is as follows:
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:
Copy code The code is as follows:
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:
Copy code The code is as follows:
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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template