1. 程式人生 > >js--屬性和方法(私有/公有)

js--屬性和方法(私有/公有)

  • 【私有變數】 在物件內部使用’var’關鍵字來宣告,而且它只能被私有函式和特權方法訪問。

  • 【私有方法】 在物件的建構函式裡宣告(或者是通過varfunctionName=function(){…}來定義),它能被特權方法呼叫(包括物件的構造方法)和私有方法呼叫,私有函式只能訪問私有的方法和屬性。

  • 【特權方法】通過this.methodName=function(){…}來宣告而且可能被物件外部的程式碼呼叫。它可以使用:this.特權函式() 方式來呼叫特權函式,使用 :私有函式()方式來呼叫私有函式。

  • 【公共屬性】 通過this.variableName來定義而且在物件外部是可以讀寫的。不能被私有函式所呼叫。

  • 【公共方法】 通過ClassName.prototype.methodName=function(){…}來定義可以從物件外部來呼叫。

  • 【原型屬性】 通過ClassName.prototype.propertyName=someValue 來定義。

  • 【靜態屬性】 通過ClassName.propertyName=someValue 來定義

  • 【靜態方法】 通過ClassName.funName=function(){…} 來定義。


function myfun1(){
	//這是私有屬性
	var private1 = "這是私有屬性";
	var privateMethod = function(){
	   alert(private1);
	}
	//這是例項屬性
	this.publicvar = "這是例項屬性";
	this.public1 = function(){
	    privateMethod();
	}
}


var newfun1 = new myfun1();
newfun1.public1(); //這是私有屬性
alert(newfun1.publicvar);//這是例項屬性
alert(newfun1.private1); // undefined   newfun1.privateMethod(); //執行錯誤

function myfun2(){

}

myfun2.staticvar = "這是靜態屬性";
myfun2.staticmethod = function(){
   alert(myfun2.staticvar);
}

var newfun2 = new myfun2();
//newfun2.staticmethod();//執行錯誤;
alert(newfun2.staticvar);//undefined
//靜態私有成員
var myfun3 = (function(){
   function privateProperty(){

   }
   privateProperty.staticvar = "這是靜態私有成員";
   privateProperty.staticmethod = function(){
       alert(privateProperty.staticvar);
   }
    privateProperty.staticmethod();
    return privateProperty

 })();

//靜態類
var funcount = 0;
var myfun4 = new function(){
   funcount++;
   this.printCount = function(){
       alert(funcount);
   }
}
myfun4.printCount(); //輸出1;
myfun4.printCount(); //輸出1;
myfun4.prototype.amethod = function(){
   alert("原型物件");
}//執行錯誤
var newfun4 = new myfun4();
newfun4.amethod();


//執行錯誤,說明myfun3建立並例項化之後就不能再為它新增方法,屬性
new myfun3.constructor().printCount();//如果你確實想例項化,這樣也可以.
//原型繼承
var myfun5 = function(){

}
myfun5.prototype.myfun5_extend = function(){
   alert("這是原型繼承的");
}
 var myfun5_sub = function(){

}
myfun5_sub.prototype = new myfun5();
var newfun5 = new myfun5_sub();
 newfun5.myfun5_extend(); //這是原型繼承的
//呼叫繼承
var myfun6 = function(){
   this.method_p = function(){
       alert("這是呼叫繼承的");
   }
}
var myfun6_sub = function(){
   myfun6.call(this);
}

var newfun6 = new myfun6_sub();
newfun6.method_p();//這是呼叫繼承的
//覆蓋
var myfun7 = function(){
   this.method = function(){
       alert("這是父物件方法");
   }
}
var myfun7_sub = function(){
   this.method = function(){
       alert("這是子物件方法");
   }
}
myfun7_sub.prototype = new myfun7();
var newfun7 = new myfun7_sub();
newfun7.method(); //這是子物件方法,父物件方法被覆蓋了.
//多型
function myfun8(a, b){
   var a = a;
   var b = b;
   if (typeof a == "number" && typeof b == "number") {
       alert(a * b);
   } else if (typeof a == "string" && typeof b == "string") {
       alert(a + b);
   } else {
       alert("輸入錯啦");
   }
}

myfun8(3, 4); // 輸出12;
myfun8("hi,", "你好");//輸出hi,你好;
myfun8("hi", 5);//輸入錯啦

原文連結:js–屬性和方法(私有/公有)

**THE END**