Copy codeThe Code is as follows:
<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 variable:" + this. pubMember + "\ n ";
Str + = "public method:" + this. pubMethod ();
Return str;
}
}
// Add public methods
// Private variables and methods cannot be called
JsClass. prototype. pubMethod = function (){
Return "pubMethod ()";
}
// Instances using JsClass
JsObject = new JsClass ("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>