Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript nesting functions and using them

Tags:

javascript

I am newer to JavaScript and come from a Java background. I am trying to write a pretty simple JavaScript application but I am having some issues. I want to duplicate a sort of class structure in JavaScript the issue I am having has to do with the scope of functions inside of functions.

I want to create a structure like this

function codeArray() {
    function create() {
        addElement( prop1, prop2,) {
            //create an element
        }

        function traverse(object) {
            //recursively go through some nested list data structure
            addElement(asd, 4534);
        }
    }

    function deleteElement() {
        //delete a single element from an array
    }

    print() {
        //print array;
    }
}

something.click(function() {
    codeArray.create();
    codeArray.print();
});

So the issue I am running into is because of the scope of the functions nested inside codeArray I cannot access them from outside codeArray. Would it be bad practice of encapsulation to just get rid of the wrapper codeArray function? Can someone suggest a better re-write for how to do this?

Thanks in advance.

like image 235
recneps Avatar asked Apr 26 '26 02:04

recneps


1 Answers

You're almost right. You should be using an object instead:

codeArray = {
    create:function() {
       // ...
    },
    // ...
    print:function() {
       // ...
    }
};

Then you can call:

codeArray.create();
codeArray.print();
like image 136
Niet the Dark Absol Avatar answered Apr 28 '26 15:04

Niet the Dark Absol