Monday, 22 March 2021

How to achieve privacy for value saved in `this` in constructor function?

What options do I have to achieve privacy on values I need to save in this in a constructor function? For example, a simple Stack implementation:

function Stack(){
  this._stack = {}
  this._counter = 0
}

Stack.prototype.push = function (item){
  this._stack[this._counter++] = item
  return this
}

Stack.prototype.pop = function (){
  Reflect.deleteProperty(this._stack, --this._counter);
  return this
}

Stack.prototype.peek = function (){
  return this._stack[this._counter - 1]
}

Stack.prototype.length = function (){
  return Object.values(this._stack).length
}

If these methods are not defined as prototype methods, I can easily private them like this:

function Stack(){
  let _stack = {}
  let _counter = 0

  this.push = function (item){
    _stack[_counter++] = item
    return this
  }

  this.pop = function (){
    Reflect.deleteProperty(_stack, --_counter);
    return this
  }

  this.peek = function (){
    return _stack[_counter - 1]
  }

  this.length = function (){
    return Object.values(_stack).length
  }
}

This way _stack and _counter are not exposed, but then these methods are not on prototype chain.

Is it possible to achieve privacy, while the protected values are saved in this?



from How to achieve privacy for value saved in `this` in constructor function?

No comments:

Post a Comment