我用方法创建了一个类:
class MyClass{
myMethod(){
return ...;
}}
之后我将该类的每个实例都推送到一个数组:
let myList = [];
myList.push(myClass)
如何在循环中调用myMethod()?此代码失败:
for (var i = 0; myList.length; i++) {
myList[i].myMethod();
}
Uncaught TypeError: Cannot read property 'myMethod' of undefined
THX, piccus
答案 0 :(得分:2)
您应该使用new
运算符创建一个实例,以便调用方法:
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();
}
如果您需要在没有实例的情况下调用此方法,请将其定义为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();
}
答案 1 :(得分:0)
当调用构造函数时,您可以通过将MyClass
推送到this
来跟踪myList
的每个实例。这样,每次构建新的myList
实例时,您都不必记住要进入MyClass
。
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();
}
&#13;