0

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!

0

1 Answer 1

2

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

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

1 Comment

Super, thank you very much, @Isaac! Could you please give me a reference as to how this method of instantiating variables and functions is called? I guess it's something like a class?

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.