Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hongbusi opened this issue Jul 7, 2022 · 2 comments
Labels
JS javascript

Comments

@Hongbusi
Copy link
Member

Hongbusi commented Jul 7, 2022

通过函数的创建形式:

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 一样还是可以访问到这个属性。

@Hongbusi Hongbusi added today 每日一题。 JS javascript labels Jul 7, 2022
@luckept
Copy link
Member

luckept commented Jul 7, 2022

闭包版

(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
Copy link

myltx commented Jul 7, 2022

// 函数实现
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())

@Hongbusi Hongbusi removed the today 每日一题。 label Jul 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JS javascript
Development

No branches or pull requests

3 participants