JavaScript--闭包与原型
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>
共同学习,写下你的评论
评论加载中...
作者其他优质文章