-1

Suppose I have this code:

function GraphFactory() {

  this.nodeNames = [];
  this.pinnedNodes = [];


  this.initPinnedNodes = function(nodes) {
    if (nodes) {
      this.pinnedNodes = nodes;
    } else {
      this.pinnedNodes = [];
    }
  }
  this.checkIfPinned = function(node) {
    if (this.pinnedNodes.indexOf(node) > -1) {
      return true;
    } else {
      return false;
    }
  }
  this.addToPinnedNodes = function(name) {
    this.pinnedNodes.push(name);
    return true;
  }
  this.removeFromPinnedNodes = function(name) {
    this.pinnedNodes.splice(this.pinnedNodes.indexOf(name), 1);
    return true;
  }
}

let graphFactory = new GraphFactory();

Right now i can access both the function

graphFactory.checkIfPinned(label);

but also directly the variable

graphFactory.pinnedNodes

How would I set things up so only the functions, but not the variables could get accessed?

Eddie
  • 26,593
  • 6
  • 36
  • 58
Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • 1
    https://stackoverflow.com/questions/2636453/is-it-possible-to-create-a-hidden-property-in-javascript is this what you're looking for? – briosheje Apr 12 '19 at 10:24

2 Answers2

1

Use variables instead of properties on the object.

let nodeNames = [];

They'll be closed over by your dynamically assigned instance methods.

Or see this question for the modern approach.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

With the current construct, you can use a closure per object, practically a local variable in your constructor function:

function GraphFactory() {
  var nodeNames = [];
  var pinnedNodes = [];

  this.initPinnedNodes = function(nodes) {
    if (nodes) {
      pinnedNodes = nodes;
    } else {
      pinnedNodes = [];
    }
  }
  this.checkIfPinned = function(node) {
    if (pinnedNodes.indexOf(node) > -1) {
      return true;
    } else {
      return false;
    }
  }
  this.addToPinnedNodes = function(name) {
    pinnedNodes.push(name);
    return true;
  }
  this.removeFromPinnedNodes = function(name) {
    pinnedNodes.splice(this.pinnedNodes.indexOf(name), 1);
    return true;
  }
}

let graphFactory = new GraphFactory();

However such variables will not be accessible to methods you add later, from outside. For example that nodeNames exists in vain this way.

tevemadar
  • 12,389
  • 3
  • 21
  • 49