1 //define a JavaScript class2 functionJsclass (Privateparam,publicparam) {//constructor Function3 varPrimember = Privateparam;//Private Variables4 This. Pubmember = Publicparam;//Public Variables5 //Defining Private Methods6 functionPrimethod () {7 return"Primethod ()";8 }9 //defines a privileged method that can access all members of a privileged methodTen This. Privilegedmethod =function(){ One varstr = "This is the privileged method, I called \ n"; Astr + = "Private variable:" + primember + "\ n"; -str + = "Private method:" + primethod () + "\ n"; -str + = "public variable:" + This. pubmember + "\ n"; thestr + = "Public method:" + This. Pubmethod (); - returnstr; - } - } + //add public methods, cannot call private variables and methods -JsClass.prototype.pubMethod =function(){ + return"Pubmethod ()"; A } at - //using an instance of Jsclass -Jsobject =NewJsclass ("Primember", "Pubmember"); - -alert (Jsobject.pubmember);//Popup pubmember Information - /* in alert (jsobject.primember);//popup Undefined information - alert (Jsobject.pubmethod ());//popup Pubmethod information to alert (Jsobject.primethod ());//Popup "object does not support this property or method" error + alert (Jsobject.privilegedmethod ()); - */
JavaScript imitates object-oriented programming instance code (private, public variable ...) )