js 类的private public属性

来源:互联网 发布:小学生学汉字软件 编辑:程序博客网 时间:2024/05/21 07:49

 

function Person(name){//私有变量privatevar address="private property";this.getAddress=function(){return address;};//公有属性publicthis.name=name;}//公共方法Person.prototype.getName=function(){return this.name;}Person.prototype.setName=function(){this.name=name;}var hb=new Person("hb");alert(hb.name);//hbalert(hb.getName());//hbalert(hb.address);//undefinedalert(hb.getAddress());//private propertyPerson.static="static property";//静态变量alert(Person.static);

 首先声明的Person函数就是一个类。用var方式声明的变量仅在内部可见,所以address是私有变量,访问address方法只有通过向外暴露的getAddress()方法得到address属性

 

不需要实例化Person类就可以访问static属性