实现一个Person类,设计下面的类
name : public
age : private
sex : private
const Person = (function() {
let _sex = '';
let _age = 0;
class Person {
constructor(name, age, sex){
this.name = name;
_age = age;
_sex = sex;
}
getName(){
return this.name;
}
getAge(){
return _age;
}
getSex(){
return _sex;
}
}
return Person;
})();
let p1 = new Person('zhangsan', 16, 'MALE');
let p2 = new Person('lisi', 43, 'FEMALE');
console.log(p1.getName(), p1.getAge(), p1.getSex(), p1.name, p1._age, p1._sex); // zhangsan 16 MALE zhangsan undefined undefined
console.log(p2.getName(), p2.getAge(), p2.getSex(), p2.name, p2._age, p2._sex); // lisi 43 FEMALE lisi undefined undefined
const Person = (function() {
const _age = Symbol('_age');
const _sex = Symbol('_sex');
class Person {
constructor(name, age, sex){
this.name = name;
this[_age] = age;
this[_sex] = sex;
}
getName(){
return this.name;
}
getAge(){
return this[_age];
}
getSex(){
return this[_sex];
}
}
return Person;
})();
let p1 = new Person('zhangsan', 16, 'MALE');
let p2 = new Person('lisi', 43, 'FEMALE');
console.log(p1.getName(), p1.getAge(), p1.getSex(), p1.name, p1._age, p1._sex); // zhangsan 16 MALE zhangsan undefined undefined
console.log(p2.getName(), p2.getAge(), p2.getSex(), p2.name, p2._age, p2._sex); // lisi 43 FEMALE lisi undefined undefined
const Person = (function() {
const _age = new WeakMap();
const _sex = new WeakMap();
class Person {
constructor(name, age, sex){
this.name = name;
_age.set(this, age);
_sex.set(this, sex);
}
getName(){
return this.name;
}
getAge(){
return _age.get(this);
}
getSex(){
return _sex.get(this);
}
}
return Person;
})();
let p1 = new Person('zhangsan', 16, 'MALE');
let p2 = new Person('lisi', 43, 'FEMALE');
console.log(p1.getName(), p1.getAge(), p1.getSex(), p1.name, p1._age, p1._sex); // zhangsan 16 MALE zhangsan undefined undefined
console.log(p2.getName(), p2.getAge(), p2.getSex(), p2.name, p2._age, p2._sex); // lisi 43 FEMALE lisi undefined undefined
const Person = (function() {
#age;
#sex;
class Person {
constructor(name, age, sex){
this.name = name;
this.#age = age;
this.#sex = sex;
}
getName(){
return this.name;
}
getAge(){
return this.#age;
}
getSex(){
return this.#sex;
}
}
return Person;
})();
let p1 = new Person('zhangsan', 16, 'MALE');
let p2 = new Person('lisi', 43, 'FEMALE');
console.log(p1.getName(), p1.getAge(), p1.getSex(), p1.name, p1._age, p1._sex); // zhangsan 16 MALE zhangsan undefined undefined
console.log(p2.getName(), p2.getAge(), p2.getSex(), p2.name, p2._age, p2._sex); // lisi 43 FEMALE lisi undefined undefined