Reputation: 1295
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.
Upvotes: 3
Views: 93
Reputation: 324630
You're almost right. You should be using an object instead:
codeArray = {
create:function() {
// ...
},
// ...
print:function() {
// ...
}
};
Then you can call:
codeArray.create();
codeArray.print();
Upvotes: 7