当前位置 : 主页 > 编程语言 > java >

JavaScript 属性私有化

来源:互联网 收集:自由互联 发布时间:2022-10-15
第一种 利用闭包+函数自执行 var Person = (function(name, gender){ var _gender; function P(name, gender){ this.name = name; _gender = gender; } P.prototype.getGender = function(){ return _gender; } return P; })() var p1 = new Pers


第一种 利用闭包+函数自执行

var Person = (function(name, gender){

var _gender;
function P(name, gender){
this.name = name;
_gender = gender;
}

P.prototype.getGender = function(){
return _gender;
}
return P;
})()


var p1 = new Person('abc', '女');
console.log(p1); // P { name: 'abc' }
console.log(p1.gender); // undefined
console.log(p1.getGender()); //女

第二种 利用ES6 新的数据类型 Symbol

var Person = (function(name, gender){

var g = Symbol('gender');
function P(name, gender){
this.name = name;
_gender = gender;
this[g] = gender;
}

P.prototype.getGender = function(){
return this[g];
}
return P;
})()


var p1 = new Person('abc', '女');
console.log(p1); //P { name: 'abc', [Symbol(gender)]: '女' }
console.log(p1.gender); //undefined
console.log(p1.getGender()); //女

2 class + Symbol

class Person{
constructor(name, gender){
this.name = name;
this[Symbol('gender')] = gender;
}

getGender(){
return this.gender;
}
}

let p = new Person('xiaoh','男');
console.log(p); // Person { name: 'xiaoh', [Symbol(gender)]: '男' }
console.log(p[Symbol('gender')]); //undefined


网友评论