Skip to content

如何实现一个私有变量, 用 getName 方法可以访问, 不能直接访问 #30

Open

Description

@Hongbusi

通过函数的创建形式:

function People() {
  var name= 'Hongbusi'  
  this.getName=function() {
    return name;
  }
}
const people = new People()
console.log(people.name)
console.log(people.getName())

另外在这里讲一下网上一种错误的实现方案,通过配置 defineProperty 的不可枚举,不可修改:

const user = {
  name: 'Hongbusi',
  getName: function() {
    return this.name
  }
}

Object.defineProperty(user, 'name', {
  // 不可枚举不可配置
})

配置不可枚举只是让某个属性不能通过 for..in 或 Object.keys() 的方式遍历出来,直接 user.name 一样还是可以访问到这个属性。

Activity

  1. luckept commented on Jul 7, 2022

    @luckept
    Member

    闭包版

    (function privateProxyProducer() {
      const privateValue = new Map();
      const ErrorMap = {
        normal: 'PrivateProxyProducer Error: 未查询到相关信息'
      };
      function errorHandler(mode = 'normal') {
        return ErrorMap[mode];
      }
      return function () {
        this.getName = (key) => {
          return privateValue.has(key) ? privateValue.get(key) : errorHandler();
        };
        this.setName = (key, value) => {
          return key && privateValue.set(key, value) && true;
        };
        this.hasName = (key) => {
          return key && privateValue.has(key)
        }
      };
    })()();
    
    setName('hi', false);
    const res1 = getName('hi2');
    console.log(res1);
    
    const a = { age: 1 };
    setName(a, 'another');
    const res2 = getName(a);
    console.log(res2);
  2. myltx commented on Jul 7, 2022

    @myltx
    // 函数实现
    function private(){
      let a = '我是私有变量';
      this.getName=function(){
      return a;
     }
    }
      const p = new private()
      console.log(p.a)
      console.log(p.getName())
    // class 实现
    class private1 {
      constructor() {
        let a = '我是私有变量';
        this.getName = function () {
          return a;
        };
      }
    }
    const p1 = new private1()
    console.log(p1.a)
    console.log(p1.getName())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    JSjavascript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions