Symbol 实现属性私有化的方式

时间:2023-03-09 16:27:39
Symbol 实现属性私有化的方式
  • //一般通过私有变量来保存私有属性 通过原型方法(getSex)来访问该属性   实现该属性只能被访问无法直接改变属性值
    const Person = (function(){
    let _sex = ""
    function P(name,sex){
    this.name = name
    _sex = sex
    }
    P.prototype.getSex = function(){
    return _sex
    }
    return P
    }())
    let P1 = new Person('张三','男')
    console.log(P1.getSex()) //使用Symbol来实现属性的私有化----ps(感觉上面的方式更好理解啊)
    const Person = (function(){
    let _sex = Symbol('sex')
    function P(name,sex){
    this.name = name
    this[_sex] = sex
    }
    P.prototype.say = function(){
    return this[_sex]
    }
    return P
    }())
    let P1 = new Person('张三','男')
    console.log(P1)
    console.log(P1.say())