Javascript私有成员的实现方式2010-02-21 博客园 陈鹤伟我之前买过一本书《Javascript高级程序设计》 Nicholas C.Zakas 著总体来讲这本书还是可以的,但看完这本书还留了几个问题一直困扰着我,如js中私有变量的实现,prototype等,经过自己一系列测试,现在终于弄明白了。很多书上都是说,Javascript是不能真正实现Javascript私有成员的,因此在开发的时候,统一约定 __ 两个下划线开头为私有变量。后来,发现Javascript中闭包的特性,从而彻底解决了Javascript私有成员的问题。function testFn(){
var _Name;//定义Javascript私有成员
this.setName = function(name){
_Name = name; //从当前执行环境中获取_Name
}
this.getName = function(){
return _Name;
}
}// End testFn
var test = testFn();
alert(typeof test._Name === "undefined")//true
test.setName("KenChen");test._Name 根本访问不到,但是用对象方法能访问到,因为闭包能从当前的执行环境中获取信息。接下来我们看看,共有成员是怎样实现的function testFn(name){
this.Name = name;
this.getName = function(){
return this.Name;
}
}
var test = new testFn("KenChen");
test.getName(); //KenChen
test.Name = "CC";
est.getName();//CC 接下来在看看类静态变量是怎样实现的function testFn(){
}
testFn.Name = "KenChen";
alert(testFn.Name);//KenChen
testFn.Name = "CC";
alert(testFn.Name);//CC关于Portotype,继承等以后的博文中叙述。