到底哪一种方式属于闭包?
浴火_凤凰 2009-11-05 02:50:27 代码段1:
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); //这里不能访问到私有变量
书上说上面是一个闭包,我怎么感觉上面的红色部分变量使用带下划线的变量代替才是闭包呢。
就像下面这样
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); //这里不能访问到私有变量
到底哪一种方式属于闭包?