Summary of methods for customizing Javascript types

Source: Internet
Author: User

1. Define the type
Copy codeThe Code is as follows:
Function UserObject (parameter ){
}

Parameter can be omitted, which is equivalent to the constructor parameter in C.
2. instantiate a custom type
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function userobject (parameter ){
}
// Myobject is now an object of type userobject!
Var myobject = new userobject ("hi ")
Alert (myobject)
</Script>

3. Add attributes
Copy codeThe Code is as follows:
Function userobject (parameter ){
This. firstproperty = parameter
This. secondproperty = "This is the second property"
}

// Use
Copy codeThe Code is as follows:
<Script>
Var myobject = new userobject ("hi there .")
// Alerts "hi there ."
Alert (myobject. firstproperty)
// Writes "This is the second property"
Document. write (myobject. secondproperty)
</Script>

4. Add method (circle class)
Copy codeThe Code is as follows:
// First method function
Function computearea (){
Var area = this. radius * this. radius * 3.14
Return area
}
// Second method function
Function computediameter (){
Var diameter = this. radius * 2
Return diameter
}

Associated with the custom type:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
/* The below creates a new object, and gives it the two methods defined earlier */
Function circle (r ){
// Property that stores the radius
This. radius = r
This. area = computearea
This. diameter = computediameter
}
</Script>

Use the custom method:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var mycircle = new circle (20)
/// Alerts 1256
Alert ("area =" + mycircle. area ())
/// Alerts 400
Alert ("diameter =" + mycircle. diameter ())
</Script>

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.