javascript类型问题:未捕获TypeError:对象0没有方法'draw'

时间:2011-12-23 15:23:32

标签: javascript oop canvas

只是尝试使用JS +画布,我似乎已经碰壁了。 我的最小应用程序的“目标”是在画布上的任意随机位置单击,按下绘制按钮并在您单击的位置绘制正方形。

来自OO背景...我(尝试)使用OO,这在js我完全没有掌握。

但基本上我有一个自定义Square对象

function Square(l, w, x, y) {

    this.length = l;
    this.width  = w;
    this.posx   = x - l/2;
    this.posy   = y - w/2;

    //test
    //ctx.fillStyle = "rgb(20,0,0)";
    //ctx.fillRect(this.posx,this.posy,this.length,this.width);


    this.draw = function() {

        ctx.fillStyle = "rgb(20,0,0)";
        ctx.fillRect(this.posx,this.posy,this.length,this.width);

    }
}

我每次用户点击时都会添加到数组中 这是我点击画布时的事件处理程序。

function addTo(evt) {

    pos = getMousePos(evt);
    var sq = new Square(50, 50, pos.x, pos.y);
    list.push(sq);

    output.innerText = "("+sq.posx+","+sq.posy+")";
}

这里是我(尝试)绘制正方形的地方。

function renderStack() {

    //alert(list);
    canvas.width = canvas.width;
    for(var o in list) o.draw();

}

这是错误:

Uncaught TypeError: Object 0 has no method 'draw'

我在尝试访问该对象的变量时遇到类似的错误。 似乎在我将它们添加到列表后,js会忘记它们是什么类型的? - 因为当我打印数组时,它充满了[对象对象]的

感谢。

2 个答案:

答案 0 :(得分:5)

for ... in ...为您提供了一个对象的而不是内容

因此,在数组中,您将收到存储元素的 indices 和任何其他可枚举属性的名称

相反,你应该使用:

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

答案 1 :(得分:4)

for(var o in list)

o是数组的索引(或属性)。您将通过list[o]访问该索引中存储的内容。

但是对于数组,最好使用Alnitak所示的for循环而不是for-in

<强>更新

当您需要遍历所有属性时,将使用For-in。由于数组是一个对象,因此它具有索引和属性。所以for-in将遍历所有索引和属性。 for-in更适合对象。

e.g。

var obj = { p1: 1, p2: 2};

for(var prop in obj) {
   //...
}