P44 1 < Script Type = " Text/JavaScript " >
2 Function Person (firstname, lastname, age) {
3 VaR _ Firstname = Firstname;
4 VaR _ Lastname = Lastname;
5
6 This . Age = Age;
7
8 This . Getname = Function () {< br> 9 return (_ firstname + " " + _ lastname); // return (firstname +" "+ lastname) is printed incorrectly)
10 }
11
12 This . Sayhello = Function () {
13Alert ("Hello, I'm" +_ Firstname+ " " +_ Lastname );
14}
15 }
16
17 VaR Billgates = New Person ( " Bill " , " Gates " , 53 );
18 VaR Stevejobs = New Person ( " Steve " , " Jobs " , 53 );
19
20 Billgates. sayhello (); // Hello, I'm Bill Gates
21 Stevejobs. sayhello (); // Hello, I'm Steve Jobs
22
23
24
25 Alert (billgates. _ firstname ); // Undefined. because _ firstname is a private variable defined in the person function body, its scope theoretically only exists in the function body that calls an instant. Once new person (XXX, XXX, XXX) is completed, _ The lifecycle of firstname should end"
26
27 Alert (billgates. getname () + " " + Billgates. Age ); // Bill Gates 53. however, in this way, the _ firstname and _ lastname can be accessed, that is, the lifecycle of the private variable is extended (although billgates cannot be used directly. _ firstname access"
28
29 Alert (billgates. sayhello = Stevejobs. sayhello ); // False. Because sayhello is not defined in the prototype chain, every object method is "independent", which wastes resources.
30
31
32 Function MAN (height) {
33This. Height=Height;
34}
35
36 Man. Prototype. getheight = Function () {
37Return This. Height;
38}
39
40
41 VaR Jimmy = New MAN ( 173 );
42
43 Alert (Jimmy. getheight ()); // 173
44
45
46 VaR Mike = New MAN ( 184 );
47 Alert (Mike. getheight ()); // 184
48
49 Alert (Jimmy. getheight = Mike. getheight ); // True. each instance of the method defined in the prototype shares the same method, and the performance is superior to the previous implementation. However, the disadvantage is that the class must be defined in two parts, not very elegant in writing"
50
51
52 < / SCRIPT>