涵盖了javascript公有成员定义、私有成员定义、特权方法定义的简单示例
- <script>
-
- function JsClass(privateParam,publicParam){
- var priMember = privateParam;
- this.pubMember = publicParam;
-
- function priMethod(){
- return "priMethod()";
- }
-
-
- this.privilegedMethod = function(){
- var str = "这是特权方法,我调用了\n";
- str += " 私有变量:" + priMember +"\n";
- str += " 私有方法:" + priMethod() +"\n";
- str += " 公共变量:" + this.pubMember +"\n";
- str += " 公共方法:" + this.pubMethod();
-
- return str;
- }
- }
-
-
- JsClass.prototype.pubMethod = function(){
- return "pubMethod()";
- }
-
-
- JsObject = new JsClass("priMember","pubMember");
-
-
-
-
-
- alert(JsObject.privilegedMethod());
- </script>
<script>
//定义一个javascript类
function JsClass(privateParam/* */,publicParam){//构造函数
var priMember = privateParam; //私有变量
this.pubMember = publicParam; //公共变量
//定义私有方法
function priMethod(){
return "priMethod()";
}
//定义特权方法
//特权方法可以访问所有成员
this.privilegedMethod = function(){
var str = "这是特权方法,我调用了\n";
str += " 私有变量:" + priMember +"\n";
str += " 私有方法:" + priMethod() +"\n";
str += " 公共变量:" + this.pubMember +"\n";
str += " 公共方法:" + this.pubMethod();
return str;
}
}
//添加公共方法
//不能调用私有变量和方法
JsClass.prototype.pubMethod = function(){
return "pubMethod()";
}
//使用 JsClass的实例
JsObject = new JsClass("priMember","pubMember");
//alert(JsObject.pubMember);//弹出pubMember信息
//alert(JsObject.priMember);//弹出undefined信息
//alert(JsObject.pubMethod());//弹出pubMethod信息
//alert(JsObject.priMethod());//弹出"对象不支持此属性或方法"的错误
alert(JsObject.privilegedMethod());
</script>