JS中的 公有變數、私有變數 !
阿新 • • 發佈:2020-09-02
公有變數、私有變數 !
初學者的見解,算是記錄學習過程,也算是分享以便共同成長,如有不正確的地方,請不要客氣的留言指出!
先看程式碼1:
function car(){ var wheel = 3; //私有變數 this.wheel = 4; //公有變數 alert(wheel); alert(this.wheel); } var car1 = new car();結果是:3 4
程式碼2:
function car(){ var wheel = 3;//私有變數 this.wheel = 4;//公有變數 } var car1 = new car(); alert(car1.wheel);結果:4
varwheel=3是區域性變數,this.wheel=4是公有變數,若想訪問car中的私有變數,請看程式碼3:
function car(){ var wheel = 3;//私有變數 this.wheel = 4;//公有變數 this.getPrivateVal = function(){ return wheel; } } var car1 = new car(); alert(car1.getPrivateVal());結果:3
實際應用舉例:
<script>
//構造一個學生物件 function student(){ var names = "wang"; // 學生的名字為私有的,不公開 (私有變數) this.profession = "Network"; //學生的專業為公有的,可以公開 (公有變數) this.getnames = function(){ // 提供一個介面,通過這個介面可以知道該學生的名字 return names; }; this.setnames = function(newname){ //提供一個介面,可以修改學生的名字 names = newname;}; } //測試 var student1 = new student(); // new 一個新的student1 alert(student1.names); //undefined ,(私有變數在函式外部不能被獲取) alert(student1.profession); //Network,(公有變數可以被獲取到,也可以把公有變數理解成全域性變數) alert(student1.getnames()); // wang ,通過專用介面,我們可以獲取到該學生的名字 student1.setnames("zhang"); //通過專用介面,我們也可以修改該學生的名字 alert(student1.getnames()); // zhang ,重新獲取該學生修改後的名字</script>