The rectangle () function is used as an example.
1. Simple Functions
Function rectangle (W, h ){
This. width = W;
This. Height = h;
}
VaR test = new rectangle (); create a simple rectangle object, including the width and height attributes
An additional function defining the calculated area transmits the test object as a parameter.
Function getrecarea (REC ){
Return rec. Width * Rec. height;
}
Console. Log (getrecarea (TEST ));
In this case, the area of any simple rectangle can be calculated.Object-Oriented Programming DesignThought, should also include the method into the "class"
Function rectangle (W, h ){
This. width = W;
This. Height = h;
This. Area = function () {return this. Width * This. Height}
}
Console. Log (test. Area ())
This is already a friendly solution, but it is not optimal. Each time a rectanlge object is created, the width and height parameters are changed, the Arec functions are the same in each rectanlge object, which reminds me ofInheritanceMechanism: Java inherits from the base class, and each object in Javascript has prototype object attributes (in fact, the prototype attribute value of this object is initialized by default after the object is created, prototype Initialization is an object that contains a constructor attribute. This is why every object has a constructor ),
Functions or attributes added from prototype will become attributes of the initialized object.
Function rectangle (W, h ){
This. width = W;
This. Height = h;
}
Rectangle. Prototype. Arec = function () {return this. Width * This. height;} // conclusion: it is a good solution to put unchanged attributes in prototype.
2. Extended built-in types
Not only do user-defined functions have prototype, but also built-in classes such as string and date in Javascript have prototype attributes;
Instance: determines whether a string ends with a specified character.
String. Prototype. isendwith = function (c ){
Return (C = This. charat (this. Length-1 ))
}
VaR S = "stringc ";
Console. Log (S. iseend ());