P44
<script type="text/javascript">
function Person(firstName,lastName,age){
var _firstName = firstName;
var _lastName = lastName;
this.age = age;
this.getName = function(){
return (_firstName + " " + _lastName);//这里书上印错为return(firstName + " " + lastName)了
}
this.SayHello = function(){
alert("Hello,I'm " + _firstName + " " + _lastName);
}
}
var BillGates = new Person("Bill","Gates",53);
var SteveJobs = new Person("Steve","Jobs",53);
BillGates.SayHello(); //Hello,I'm Bill Gates
SteveJobs.SayHello(); //Hello,I'm Steve Jobs
alert(BillGates._firstName);//undefined. 因为_firstName为Person函数体内部定义的私有变量,其作用域理论上讲只能存在于调用瞬间的函数体内,一旦new Person(xxx,xxx,xxx)完成后,_firstName的生命周期就“理应结束"
alert(BillGates.getName() + " " + BillGates.age);//Bill Gates 53.但是通过这种方式使得_firstName,_lastName可以继续被访问得到,即:私有变量的生命周期被延长了(虽然不能直接用BillGates._firstName访问),这种现象就是传说中的"闭包"
alert(BillGates.SayHello == SteveJobs.SayHello);//false.因为SayHello不是从原型链上定义的,所以每个对象的方法都是"独立的"一份,浪费了资源
function Man(height){
this.height = height;
}
Man.prototype.GetHeight = function(){
return this.height;
}
var jimmy = new Man(173);
alert(jimmy.GetHeight());//173
var mike = new Man(184);
alert(mike.GetHeight());//184
alert(jimmy.GetHeight == mike.GetHeight);//true .从原型上定义的方法,其每个实例都共享同一份方法,性能上高优于以前的实现,但是不足之处是必须把类分成二部分定义,写法上不太"优雅"
</script>