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>