Aerodynamika
Aerodynamika

Reputation: 8413

How to create global variables functions in Javascript

I want to create a global function accessible everywhere in my script that would deal with a Graph object — constructing it, updating it, etc.

I made a function:

function GraphFactory(){
            this.initNames = function(nodes) {
                nodeNames = nodes;
            }
            this.getNodeNames = function() {
                return nodeNames;
            }
            this.addNameToNodeNames = function(name) {
                nodeNames.push(name);
                return true;
            }
        }

Then when I try to populate it using

 GraphFactory.initNames(['hello','boo'])

It says GraphFactory.initNames is not a function...

How could I use this to populate that graph object with the node names and then get a list of them using GraphFactory.getNodeNames()?

Thank you!

Upvotes: 0

Views: 35

Answers (1)

Isaac Vidrine
Isaac Vidrine

Reputation: 1666

Set a property on the class called nodeNames, then instantiate the object.

function GraphFactory(){
    this.nodeNames= [];
    this.initNames = function(nodes) {
        this.nodeNames = nodes;
    }
    this.getNodeNames = function() {
        return this.nodeNames;
    }
    this.addNameToNodeNames = function(name) {
        this.nodeNames.push(name);
        return true;
    }
}

let graphFactory = new GraphFactory();
graphFactory.initNames(['hello','boo'])
console.log(graphFactory.getNodeNames());

Upvotes: 2

Related Questions