在javascript里边,封装只体现public、private这个两个特性。
public 公开的:在构造函数里边通过this关键字声明的成员都是公开的,函数内部、外部都可以调用。
private私有的:在构造函数里边声明局部变量,就是私有成员,只有内部函数可以调用。
代码块
<script type="text/javascript">
var stronger_secret = "每天早上健身 ";
function Person(){
//私有成员( private, 构造函数内的局部变量为私有成员)。
var secret = "每天早上跑步";
var test = function (){
console.log("test ,body!!")
}
//公开成员(public, 用this 关键字声明的成员为公开成员)。
this.leg = 2;
this.run = function(){
console.log("I have "+this.leg +" 条腿,跑的很快!");
}
//对外公开的接口,内部可以访问私有成员。
this.speakSecret = function(){
//内部环境 可以访问外部环境的变量
console.log("健康秘诀:"+secret);
}
this.strongerSecret = function(){
console.log("强壮秘诀:"+stronger_secret);
}
}
**测试结果:**
var cooper = new Person();
console.log(cooper.leg); // 2
cooper.run(); // I have 2 条腿,跑的很快!
console.log(cooper.secret); // undefined
cooper.test(); // Uncaught TypeError: cooper.test is not a function
cooper.speakSecret(); // 健康秘诀:每天早上跑步 注:私有成员通过公开的接口方法可以被访问。
cooper.strongerSecret(); // 强壮秘诀:每天早上健身
</script>
这里有一个地方需要注意,函数内部声明私有变量的时候,一定要使用var命令。如果不用的话,你实际上声明了一个全局变量!
function f1(){
n=999;
}
f1();
alert(n); // 999