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(){
9
return (_firstName + " " + _lastName);//这里书上印错为return(firstName + " " + lastName)了
10
}
11
12
this.SayHello = function(){
13
alert("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. 因为_firstName为Person函数体内部定义的私有变量,其作用域理论上讲只能存在于调用瞬间的函数体内,一旦new Person(xxx,xxx,xxx)完成后,_firstName的生命周期就“理应结束"
26
27
alert(BillGates.getName() + " " + BillGates.age);//Bill Gates 53.但是通过这种方式使得_firstName,_lastName可以继续被访问得到,即:私有变量的生命周期被延长了(虽然不能直接用BillGates._firstName访问),这种现象就是传说中的"闭包"
28
29
alert(BillGates.SayHello == SteveJobs.SayHello);//false.因为SayHello不是从原型链上定义的,所以每个对象的方法都是"独立的"一份,浪费了资源
30
31
32
function Man(height){
33
this.height = height;
34
}
35
36
Man.prototype.GetHeight = function(){
37
return 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 .从原型上定义的方法,其每个实例都共享同一份方法,性能上高优于以前的实现,但是不足之处是必须把类分成二部分定义,写法上不太"优雅"
50
51
52
</script>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52
