封装
在js中,封装只体现public private
public公开的,在构造函数里面通过this关键字声明的成员都是公开的,函数内部、外部都可以调用private私有的,在构造函数里声明的局部变量,就是私有成员
<span style="font-family:Microsoft YaHei;"><script type="text/javascript">
function Animal(){
var secret = "我是一只猫";//局部变量 private
var eat = function(){//局部变量 private
console.log('我喜欢吃鱼');
}
this.leg = 4;//全局变量 public
this.run = function(){
console.log('我有'+this.leg+'腿');
}
this.fight = function(){
console.log('我赢了'+secret);
}
}
var cat = new Animal();
console.log(cat.leg);//4
cat.run();//我有4腿
console.log(cat.secret);//我是一只猫
cat.fight();// 我赢了我是一只猫
</script></span>