0

I have two objects and one array.

I have an array with values:

var a1 = ['case1','case2','case3'];

Then in another object, I work with the array by passing it in as context.

var obj2 = {
    init: function(context){
       for( var elem in context) {
          // do stuff with the elements
       }
    }
}

I also have another object that I pass the object into the same way.

var obj3 = {
    init: function(context){
       for( var elem in context) {
          // do stuff with the elements
       }
    }
}

Then I execute the init functions as such:

obj2.init(a1);
obj3.init(a1);

Another way I could do this would be as shown below, without passing the array in to the init function, and just referencing the array directly.

var obj2 = {
    init: function(){
       for( var elem in a1) {
          // do stuff with the elements and access directly to the obj1 array
       }
    }
}
var obj3 = {
    init: function(){
       for( var elem in a1) {
          // do stuff with the elements and access directly to the obj1 array
       }
    }
}

obj2.init();
obj3.init();

What affect would this have on my code?

Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
dexhering
  • 422
  • 3
  • 13
  • 3
    You shouldn't [iterate arrys with `for..in`](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea), use regular `for` loop instead. – Teemu Sep 08 '15 at 16:06
  • 5
    I'm not sure what your question is. – Blazemonger Sep 08 '15 at 16:06
  • 1
    both are correct, depends on your needs. I would pick number 2. But number 1 is an option too if you need to change context – bto.rdz Sep 08 '15 at 16:06
  • 1
    How decoupled/reusable do you want your objects to be? There's your answer. – James Thorpe Sep 08 '15 at 16:07
  • yes, i don't need change the context, just work with the values, and the object need be reusables by others parts, thanks. – dexhering Sep 08 '15 at 16:10

1 Answers1

0

This question is really a question about design. In the first case (where you pass in the array as a parameter), you've achieved low coupling. Your function does not need to know about the environment with which it's being called in. If, for whatever reason, you need to call this object with another array, you're free to do so. In the second example, your function has a dependency on the a1 array being defined outside of that object. This hurts re-usability, but that may not be an issue depending on the scope of your project. In the end, it's all about being pragmatic. In my opinion though, it's not too hard to just pass the array as a parameter, just in case you need to use it again some other time with a different array. It's just good practice.

Carlos Rodriguez
  • 2,190
  • 2
  • 18
  • 29