developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

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

Open Hongbusi opened 2 years ago

Hongbusi commented 2 years ago

通过函数的创建形式:

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..inObject.keys() 的方式遍历出来,直接 user.name 一样还是可以访问到这个属性。

luckept commented 2 years ago

闭包版

(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);
myltx commented 2 years ago
// 函数实现
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())