简体   繁体   中英

Calling a method on every instance of a class in Javascript?

I am trying to call a class' method on every instance of that class.

Currently, I have all of my classes stored in an array, called checkers[]

I loop through every instance of the class Checker() using this for loop:

this.drawCheckers = function() {
    for(var checker in this.checkers) {
        checker.draw();
    }
}

When I run the code, I get the error: localcheckers.js:57 Uncaught TypeError: checker.draw is not a function

How would I fix this?

In your for...in loop, the value stored in checker is not the property in this.checkers, but the property name.

What you need to do is access the property then call draw on it.

this.drawCheckers = function() 
{
    for(var checker in this.checkers) {
        this.checkers[checker].draw();
    }
}

See a working example here: https://jsbin.com/fezixaboso/edit?js,console

call draw() only if checker is an instance of Checker

this.drawCheckers = function() {
    for(var i = 0; i < this.checkers.length; i++) {
        if(this.checkers[i] instanceof Checker)
            this.checkers[i].draw();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM