-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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Use let when declaring the variable.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.