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

4
  • 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. Commented May 30, 2016 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? Commented May 30, 2016 at 16:08
  • Are you sure you are using new to create Foo instances? Commented May 30, 2016 at 16:14
  • Try to invoke a function, outside a loop first, to see if there is any problem. Commented May 30, 2016 at 16:21

2 Answers 2

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"]);

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.