P44 1<script type="text/javascript">
2function Person(firstName,lastName,age){
3 var _firstName = firstName;
4 var _lastName = lastName;
5
6 this.age = age;
7
8 this.getName = function(){
9 return (_firstName + " " + _lastName);//這裡書上印錯為return(firstName + " " + lastName)了
10 }
11
12 this.SayHello = function(){
13 alert("Hello,I'm " + _firstName + " " + _lastName);
14 }
15}
16
17var BillGates = new Person("Bill","Gates",53);
18var SteveJobs = new Person("Steve","Jobs",53);
19
20BillGates.SayHello(); //Hello,I'm Bill Gates
21SteveJobs.SayHello(); //Hello,I'm Steve Jobs
22
23
24
25alert(BillGates._firstName);//undefined. 因為_firstName為Person函數體內部定義的私人變數,其範圍理論上講只能存在於調用瞬間的函數體內,一旦new Person(xxx,xxx,xxx)完成後,_firstName的生命週期就“理應結束"
26
27alert(BillGates.getName() + " " + BillGates.age);//Bill Gates 53.但是通過這種方式使得_firstName,_lastName可以繼續被訪問得到,即:私人變數的生命週期被延長了(雖然不能直接用BillGates._firstName訪問),這種現象就是傳說中的"閉包"
28
29alert(BillGates.SayHello == SteveJobs.SayHello);//false.因為SayHello不是從原型鏈上定義的,所以每個對象的方法都是"獨立的"一份,浪費了資源
30
31
32function Man(height){
33 this.height = height;
34}
35
36Man.prototype.GetHeight = function(){
37 return this.height;
38}
39
40
41var jimmy = new Man(173);
42
43alert(jimmy.GetHeight());//173
44
45
46var mike = new Man(184);
47alert(mike.GetHeight());//184
48
49alert(jimmy.GetHeight == mike.GetHeight);//true .從原型上定義的方法,其每個執行個體都共用同一份方法,效能上高優於以前的實現,但是不足之處是必須把類分成二部分定義,寫法上不太"優雅"
50
51
52</script>