【私有變量】 在對象內部使用'var'關鍵字來聲明,而且它只能被私有函數和特權方法訪問。
【私有方法】 在對象的構造函數里聲明(或者是通過varfunctionName=function(){...}來定義),
它能被特權方法調用(包括對象的構造方法)和私有方法調用,私有函數只能訪問私有的方法和屬性。
【特權方法】通過this.methodName=function(){...}來聲明而且可能被對象外部的代碼調用。
它可以使用:this.特權函數() 方式來調用特權函數,使用 :私有函數()方式來調用私有函數。
【公共屬性】 通過this.variableName來定義而且在對象外部是可以讀寫的。不能被私有函數所調用。
【公共方法】 通過ClassName.prototype.methodName=function(){...}來定義可以從對象外部來調用。
【原型屬性】 通過ClassName.prototype.propertyName=someValue 來定義。
【靜態屬性】 通過ClassName.propertyName=someValue 來定義。
【靜態方法】 通過ClassName.funName=function(){...} 來定義。
1 function myfun1(){
2 //這是私有屬性
3 var private1 = "這是私有屬性";
4 var privateMethod = function(){
5 alert(private1);
6 }
7 //這是實例屬性
8 this.publicvar = "這是實例屬性";
9 this.public1 = function(){
10 privateMethod();
11 }
12 }
1 var newfun1 = new myfun1();
2 newfun1.public1(); //這是私有屬性
3 alert(newfun1.publicvar);//這是實例屬性
4 alert(newfun1.private1); // undefined newfun1.privateMethod(); //運行錯誤
1 function myfun2(){
2 }
3 myfun2.staticvar = "這是靜態屬性";
4 myfun2.staticmethod = function(){
5 alert(myfun2.staticvar);
6 }
7 var newfun2 = new myfun2();
8 //newfun2.staticmethod();//運行錯誤;
9 alert(newfun2.staticvar);//undefined
1 //靜態私有成員
2 var myfun3 = (function(){
3 function privateProperty(){
4
5 }
6 privateProperty.staticvar = "這是靜態私有成員";
7 privateProperty.staticmethod = function(){
8 alert(privateProperty.staticvar);
9 }
10 privateProperty.staticmethod();
11 return privateProperty
12 })();
1 //靜態類
2 var funcount = 0;
3 var myfun4 = new function(){
4 funcount++;
5 this.printCount = function(){
6 alert(funcount);
7 }
8 }
9 myfun4.printCount(); //輸出1;
10 myfun4.printCount(); //輸出1;
11 myfun4.prototype.amethod = function(){
12 alert("原型對象");
13 }//運行錯誤
14 var newfun4 = new myfun4();
15 newfun4.amethod();
1 //運行錯誤,說明myfun3創建並實例化之后就不能再為它添加方法,屬性
2 new myfun3.constructor().printCount();//如果你確實想實例化,這樣也可以.
3 //原型繼承
4 var myfun5 = function(){
5
6 }
7 myfun5.prototype.myfun5_extend = function(){
8 alert("這是原型繼承的");
9 }
10 var myfun5_sub = function(){
11
12 }
13 myfun5_sub.prototype = new myfun5();
14 var newfun5 = new myfun5_sub();
15 newfun5.myfun5_extend(); //這是原型繼承的
16 //調用繼承
17 var myfun6 = function(){
18 this.method_p = function(){
19 alert("這是調用繼承的");
20 }
21 }
22 var myfun6_sub = function(){
23 myfun6.call(this);
24 }
25
26 var newfun6 = new myfun6_sub();
27 newfun6.method_p();//這是調用繼承的
28 //覆蓋
29 var myfun7 = function(){
30 this.method = function(){
31 alert("這是父對象方法");
32 }
33 }
34 var myfun7_sub = function(){
35 this.method = function(){
36 alert("這是子對象方法");
37 }
38 }
39 myfun7_sub.prototype = new myfun7();
40 var newfun7 = new myfun7_sub();
41 newfun7.method(); //這是子對象方法,父對象方法被覆蓋了.
42 //多態
43 function myfun8(a, b){
44 var a = a;
45 var b = b;
46 if (typeof a == "number" && typeof b == "number") {
47 alert(a * b);
48 } else if (typeof a == "string" && typeof b == "string") {
49 alert(a + b);
50 } else {
51 alert("輸入錯啦");
52 }
53 }
54
55 myfun8(3, 4); // 輸出12;
56 myfun8("hi,", "你好");//輸出hi,你好;
57 myfun8("hi", 5);//輸入錯啦.
