A simple JavaScript class definition example
A simple example of JavaScript Public Member definition, Private member definition, and privileged method definition is provided.
Java code
- <SCRIPT>
- // Define a javascript class
- Function jsclass (privateparam/**/, publicparam) {// Constructor
- VaR primember = privateparam; // Private variable
- This. Pubmember = publicparam; // public variable
- // Define a private Method
- Function primethod (){
- Return"Primethod ()";
- }
- // Define the privileged method
- // The privileged method can access all members.
- This. Privilegedmethod = function (){
- VaR STR = "this is a privileged method. I called/N ";
- STR + = "private variable:" + primember + "/N ";
- STR + = "Private method:" + primethod () + "/N ";
- STR + = "public variables:" +This. Pubmember + "/N ";
- STR + = "public method:" +This. Pubmethod ();
- ReturnSTR;
- }
- }
- // Add public methods
- // Private variables and methods cannot be called
- Jsclass. Prototype. pubmethod = function (){
- Return"Pubmethod ()";
- }
- // Instances using jsclass
- Jsobject =NewJsclass ("primember", "pubmember ");
- // Alert (jsobject. pubmember); // The pubmember information is displayed.
- // Alert (jsobject. primember); // The undefined information is displayed.
- // Alert (jsobject. pubmethod (); // The pubmethod information is displayed.
- // Alert (jsobject. primethod (); // The error "the object does not support this attribute or method" is displayed.
- Alert (jsobject. privilegedmethod ());
- </SCRIPT>