1

I have an object called foo:

function Foo(){
  this.conceal = function(){ ... };
};

and a method called toggleView, which iterates through a collection of foo and calls conceal() method on each instance:

function toggleView(foos){
  for(a in foos){
    foos[a].conceal();
  }
}

and, of course, foos[a].conceal(); returns: conceal is not a function

dimitry_n
  • 2,939
  • 1
  • 30
  • 53
  • There's not enough code here to see what's wrong. If `foos` really is an array, you should use a plain `for` loop with a numeric index, or else `.forEach()`, to iterate. However, what you've got should work unless `foos` is *not* what you say it is. – Pointy May 30 '16 at 16:05
  • The loop is visiting a property that doesn't hold an instance of `Foo`. Note that `for..in` loops aren't strictly limited to indexes. Related: [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Jonathan Lonowski May 30 '16 at 16:08
  • Are you sure you are using `new` to create Foo instances? – elmasse May 30 '16 at 16:14
  • Try to invoke a function, outside a loop first, to see if there is any problem. – Walle Cyril May 30 '16 at 16:21

2 Answers2

1

function Foo(){
  this.conceal = function( item ) { 
    console.log(item); // "a" "b" "c"
  };
};

function toggleView(foos) {
  var myFoo = new Foo();      // Create new instance (here or outside this fn)
  for(a in foos){
    myFoo.conceal(foos[a]);   // use your instance and pass as items arg. reference
  }
}

toggleView(["a","b","c"]);

Example making toggleView a prototype of Foo

function Foo(){
  this.conceal = function( item ) { 
    console.log(item); // "a" "b" "c"
  };
}

Foo.prototype.toggleView = function(foos) {
  for(a in foos){
    this.conceal(foos[a]);        // invoke .conceal Method using `this` reference
  }
}

var myFoo = new Foo();            // Create new instance
myFoo.toggleView(["a","b","c"]);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

You should at some point call the function Foo so that the conceal becomes a "function".

Gar
  • 852
  • 13
  • 20