I would like to refactor my working code to a better structured javascript. At this moment I have something like this:
function Search(){
addNode = function(nodeToAdd){
//do something
}
function update(){
var node = aKindOfObjectFromSomeLibrary;
node.on('click', function(d){
$.each(someArray, function(i){
addNode(this);
}
}
}
}
The objective is to create a Search object with it method that can be used even outside like this:
var s = new Search();
s.addNode(nodeToAdd);
I was thinking about doing this:
function Search(){
this.addNode = function(nodeToAdd){}
}
But then the function addNode will be not accessible inside a nested generic function.
Another way I was studying is the use of this structure:
(function(){
var object = {
var field = itsValue,
addNode : function(){}
};
)();
But of course the problem of recalling the method inside a nested structure still remains.
Can you please direct me to the correct way of refactoring my code, is the only way to have that working to pass a
var scope = thisinside the nested function?
I am also referring to this Q&A in stackoverflow: How to "properly" create a custom object in JavaScript?
With the difference that, by now, I don't have to subclass my object (and this is the reason why I tried the
(function(){})();closure structure.