Home > Back-end >  How to prevent an object from being accessed JS
How to prevent an object from being accessed JS

Time:09-26

I have a program in which I wish to prevent anyone from accessing String object or any of its prototypes and I can't seem to find how to do that.

Tried Object.seal, Object.freeze and they both obviously don't work (since they don't prevent you from accessing properties already present, so feeling a little lost on how to do that. Tried looking it up on internet but after half an hour, all I have got is different way to access properties and 3 ways of adding new stuff and locking but 0 ways to make it be inaccessible

I tried to delete as well but that one was.....

CodePudding user response:

You can use a symbol as a key and store your object in that object. So It will be accessible just in scope you defined the symbol.

function addPrivateKey(a, value) {
  let sym1 = Symbol()
  a[sym1] = value
  console.log(a)
  console.log(a[sym1])
}

let a = {};
addPrivateKey(a, 2)
console.log(Object.keys(a))


Define a private scope and store your keys there. The values are accessible just with their hints!

class PrivateScope {
  glob = {};
  #keyToSym = {};
  counter = 0;
  
  get(hint) {
    return this.glob[this.#keyToSym[hint]]
  }
  
  set(value) {
    let sym1 = Symbol()
    this.glob[sym1] = value
    this.#keyToSym[this.counter] = sym1;
    return this.counter   ;
  }
}

const myPrivateScope = new PrivateScope();

let hint = myPrivateScope.set(2)

console.log(
  myPrivateScope.get(hint)
)

console.log(myPrivateScope.glob)

  • Related