JavaScript defines methods for classes and objects _javascript tips

Source: Internet
Author: User

The examples in this article describe the way JavaScript defines classes and objects. Share to everyone for your reference. The 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 any friend found that there is wrong, please tell them, learn together.
JS defines a class with two methods (I only know these two):

1. How to define a function:
Defined:

Copy Code code as follows:
function ClassA (a)
{
This.aaa=a; Add a property
This.methoda=function (PPP)//Add a method
{
Alert (PPP);
}
}
ClassA.prototype.color = "Red"; Adding the properties of an object with the prototype method also applies to instances of the class (object)
ClassA.prototype.tellColor = function ()///method to add an object with the prototype method, and this method also applies to instances of the class (object)
{
Return ' color of ' +this.name+ ' is ' +this.color;
}

How to use:
Copy Code code as follows:
var oclassa=new classa (' This is a class example! '); Instantiating classes
var temp=oclassa.aaa; Use Properties AAA
Oclassa.methoda (temp); How to use MethodA


2. How to instantiate the object class first
Defined:
Copy Code code as follows:
var oclassa=new Object (); Instantiate the underlying class object first
Oclassa.aaa= ' is a class example! '; Add a property
Oclassa.methoda=function (PPP)//Add a method
{
Alert (PPP);
}
OclassA.prototype.color = "Red"; To add an object's properties by using the prototype method
OclassA.prototype.tellColor = function ()//method to add an object using the prototype method
{
Return ' color of ' +this.name+ ' is ' +this.color;
}


How to use:
Can be used directly with Oclassa, such as:
Copy Code code as follows:
var temp=oclassa.aaa; Use Properties AAA
Oclassa.methoda (temp); How to use MethodA

I hope this article will help you with your JavaScript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.