3

I created a class with a method:

class MyClass{

myMethod(){
    return ...;
}}

After that I push every instance of that class to an array:

let myList = [];
myList.push(myClass)

How can I call myMethod() within a loop? This code fails:

for (var i = 0; myList.length; i++) {
    myList[i].myMethod();
}

Uncaught TypeError: Cannot read property 'myMethod' of undefined

Thx, piccus

0

2 Answers 2

2

You should crate an instance with new operator in order to call a method:

class myClass{
  myMethod(){
    console.log('hi');
  }
}

let myList = [];
myList.push(new myClass())
myList.push(new myClass())
myList.push(new myClass())
myList.push(new myClass())
myList.push(new myClass())

for (var i = 0; i < myList.length; i++) {
    myList[i].myMethod();
}

If you need to call this method without instance, define it as static:

class myClass{
  static myMethod(){ // notice static
    console.log('hi');
  }
}

let myList = [];
myList.push(myClass)
myList.push(myClass)
myList.push(myClass)
myList.push(myClass)
myList.push(myClass)

for (var i = 0; i < myList.length; i++) {
    myList[i].myMethod();
}

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

1 Comment

thank you. The problem was my bad-designed loop. I missed to define a condition to end the loop.
0

You could keep track of each instance of MyClass by pushing this into myList when the constructor is called. That way you don't have to keep remembering to push into myList each time you construct a new MyClass instance.

var myList = [];

function MyClass (theAnswer) {
  this.theAnswer = theAnswer;  
  this.getTheAnswer = function () {
    console.log(this.theAnswer);
  };
  
  // Keep track of all instances of MyClass here.
  myList.push(this);
}

new MyClass(42);
new MyClass(null);
new MyClass('Dunno');

for (var i = 0; i < myList.length; i++) {
    myList[i].getTheAnswer();
}

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.