简体   繁体   中英

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!

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()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM