js 共有屬性私有屬性
阿新 • • 發佈:2018-02-14
sna 方法 undefined pos 函數 屬性 head span 實例化
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 9 </body> 10 </html> 11 <script> 12 //對象構造函數 13 // 私有屬性好處: 安全 就類似閉包中的函數一樣 減少汙染 14 function Person(name) {15 //私有屬性,只能在對象構造函數內部使用 16 var className = "用戶對象"; 17 //公有屬性,在對象實例化後調用 18 this.name = name; 19 //私有方法 20 var privateFunction = function () { 21 alert(this.name); 22 } 23 //公有方法 24 this.publicFunction = function () { 25 alert(this.name); //公有屬性 26 alert(className); //正確 直接通過變量名訪問 27 alert(this.className); //undefined 錯誤 不能這樣訪問 28 } 29 //公有屬性 30 alert(className); 31 //正確 直接通過變量名訪問 32 alert(this.className); //undefined 錯誤 不能這樣訪問 33 } 34 35 /*什麽是公有屬性:*/ 36 /*使用象的人可以訪問到對象內部的某個屬性*/ 37 var person = new Person(‘xiaowang‘) 38 39 console.log(person.className); 40 console.log(person.name) 41 console.log(person.publicFunction()) 42 console.log(person.privateFunction()) 43 44 </script>
js 共有屬性私有屬性