属性私有化——数据保护
//可修改
function Person(name, gender){
this.name = name;
this.gender = gender;
}
var p1 = new Person('莫莫', '女');
私有属性
var Person = (function(){
var _gender = '';
function P(name, gender){
this.name = name;
_gender = gender;
}
P.prototype.getGender = function(){
return _gender;
}
return P;
})()
var p1 = new Person('莫莫', '女');
//p1得不到gender
//p1.getGender() 才能得到 gender
使用Symbol
var Person = (function(){
var _gender = Symbol('gender');
function P(name, gender){
this.name = name;
this.[_gender] = gender;
}
return P;
})()
var p1 = new Person('莫莫', '女');
//打印p1看得见女,取不到,外部访问不了
网友评论