javascript 闭包和原型
闭包
function Person(firstName, lastName, age)
{
//私有变量:
var _firstName = firstName;
var _lastName = lastName;
//公共变量:
this.age = age;
//方法:
this.getName = function()
{
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();
SteveJobs.SayHello();
alert(BillGates.getName() + " " + BillGates.age);
alert(BillGates.firstName); //这里不能访问到私有变量
{
//私有变量:
var _firstName = firstName;
var _lastName = lastName;
//公共变量:
this.age = age;
//方法:
this.getName = function()
{
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();
SteveJobs.SayHello();
alert(BillGates.getName() + " " + BillGates.age);
alert(BillGates.firstName); //这里不能访问到私有变量
原型
function Circle(x,y,r){
this.x = x;
this.y = y;
this.r = r;
//this.prototype = null ; /*这句代码可以看作是隐含存在的,因为javascript 中“类”的定义和函数的定义结构上没有差异,所以可以说,所有函数都隐藏有这样一个属性。*/
}
Circle.prototype.area = function(){
return this.r * this.r * 3.14159 ;
}
var circ = new Circle(0,0,2) ;
alert(circ.area()) ;
this.x = x;
this.y = y;
this.r = r;
//this.prototype = null ; /*这句代码可以看作是隐含存在的,因为javascript 中“类”的定义和函数的定义结构上没有差异,所以可以说,所有函数都隐藏有这样一个属性。*/
}
Circle.prototype.area = function(){
return this.r * this.r * 3.14159 ;
}
var circ = new Circle(0,0,2) ;
alert(circ.area()) ;