JavaScript --用ES5实现实现私有变量

 1 function Person(name){
 2     var _name=name;
 3     this.getName=function(){
 4         console.log(_name)
 5     }  
 6 }
 7 
 8 var p=new Person('bibibi');
 9 
10  console.log(p._name);//undefined
11  console.log(p.getName());//bibibi

这种方式是基于闭包来实现的。构造函数中定义一个局部变量和一个使用这个局部变量的内部函数。可以实现私有属性的隐藏,Person不能通过实例化对象获取 _name 的值,只能通过这个内部函数getName来获取。

 

posted @ 2020-06-29 17:39  软妹酸  阅读(828)  评论(0编辑  收藏  举报