ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

涂鸦智能关于es5模拟静态方法以及私有变量 #62

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

参考文献

ES5 中模拟 ES6 的 Symbol 实现私有成员

ZhengXingchi commented 4 years ago
 // es6中实现私有属性,存在缺陷
    class Person {
      constructor(name) {
        let _name = Symbol()
        this[_name] = name
      }
      get name() {
        return this[_name]
      }
    }

    // 封装_name
    var Person = (function () {
      let _name = Symbol();
      class Person {
        constructor(name) {
          this[_name] = name
        }
        get name() {
          return this[_name]
        }
      }
    })()
    // es5中封装
    var Person = (function () {
      var _name = "00" + Math.random();
      function Person(name) {
        this[_name] = name
      }
      Object.definedProperty(Person.prototype, "name", {
        get: function () {
          return this[_name]
        }
      })
    })()