如何对对象的所有属性调用函数

How to call a function on all of an object's properties?

本文关键字:属性 调用 函数 对象      更新时间:2023-09-26

>我正在制作一个游戏,其中我有多个图块对象存储在一个数组中,我正在尝试调用函数"update",将图块绘制到屏幕上。

我的脚本:

var canvas = document.getElementById("game canvas");
canvas.width = 600;
canvas.height = 300;
var g = canvas.getContext("2d");
var grass = new Image();
grass.src = "grass.png";
setInterval(draw,1000/60);
function tile(x,y,img) {
    this.x = x;
    this.y = y;
    this.img = img;
    this.update = function() {
        g.drawImage(this.img,this.x,this.y);
    }
}
var maps = {
    map1:{
        tiles:[
            new tile(0,0,grass),
            new tile(0,32,grass)
        ],
        update:function() {
            for (var i in this.tiles) {
                i.update();
            }
        }
    }
};
function draw() {
    maps.map1.update();
}

我还尝试使用对象而不是数组作为平铺容器,但也没有用。它将此错误输出到控制台:

TypeError: i.update is not a function

当您使用 for...在循环中,i实际上指的是对象的属性名称。在这种情况下,tiles是一个数组,因此i可以被认为是该数组的索引(但要小心,JS中的数组基本上只是以索引作为属性名称的特殊对象)。

但是,正如@jfriend00注释中指出的那样,for..in将枚举对象的所有属性,因此可以访问一些可能不是您期望的内容,或者没有要调用update()的对象。

虽然您可以这样做:

update:function() {
    for (var i in this.tiles) {
        // get the current tile
        this.tiles[i].update();
    }
}
最好在

数组上使用 forEach 循环,或使用标准for循环:

update:function() {
    // update each tile
    this.tiles.forEach(function(tile) {
        tile.update();
    }
}

update:function() {
    // normal for loop for safe indexing
    for (var i = 0; i < this.tiles.length; i++) {
        this.tiles[i].update();
    }
}

有关输入的更多信息

SO Answer,谈论所有类型的迭代技术