簡體   English   中英

JavaScript'不是函數' - 對象實例

[英]JavaScript 'is not a function' - object instance

我收到錯誤:

未捕獲的TypeError:rect.drawIt不是函數

我不明白為什么會發生這種錯誤? 我的意思是我在這里做同樣的事情: http//www.w3schools.com/js/js_object_prototypes.asp

  var context = document.getElementById("canv").getContext("2d"); for (var k = 0; k < 4; k++) { var rect = new Recta(); rect.drawIt(); } function Recta() { this.x1 = Math.floor(Math.random() * context.canvas.width); this.y1 = Math.floor(Math.random() * context.canvas.height); this.x2 = Math.floor(Math.random() * context.canvas.width); this.y2 = Math.floor(Math.random() * context.canvas.height); this.x3 = Math.floor(Math.random() * context.canvas.width); this.y3 = Math.floor(Math.random() * context.canvas.height); this.x4 = Math.floor(Math.random() * context.canvas.width); this.y4 = Math.floor(Math.random() * context.canvas.height); }; Recta.drawIt = function () { context.moveTo(this.x1, this.y1); context.lineTo(this.x2, this.y2); context.stroke(); context.moveTo(this.x2, this.y2); context.lineTo(this.x3, this.y3); context.stroke(); context.moveTo(this.x3, this.y3); context.lineTo(this.x4, this.y4); context.stroke(); context.moveTo(this.x4, this.y4); context.lineTo(this.x1, this.y1); context.stroke(); }; 
 <canvas id="canv"></canvas> 

首先定義Recta.prototype.drawIt然后使用它。

 function Recta() {
    this.x1 = Math.floor(Math.random() * context.canvas.width);
    this.y1 = Math.floor(Math.random() * context.canvas.height);
    this.x2 = Math.floor(Math.random() * context.canvas.width);
    this.y2 = Math.floor(Math.random() * context.canvas.height);
    this.x3 = Math.floor(Math.random() * context.canvas.width);
    this.y3 = Math.floor(Math.random() * context.canvas.height);
    this.x4 = Math.floor(Math.random() * context.canvas.width);
    this.y4 = Math.floor(Math.random() * context.canvas.height);
};

Recta.prototype.drawIt = function () {
    context.moveTo(this.x1, this.y1);
    context.lineTo(this.x2, this.y2);
    context.stroke();

    context.moveTo(this.x2, this.y2);
    context.lineTo(this.x3, this.y3);
    context.stroke();

    context.moveTo(this.x3, this.y3);
    context.lineTo(this.x4, this.y4);
    context.stroke();

    context.moveTo(this.x4, this.y4);
    context.lineTo(this.x1, this.y1);
    context.stroke();
};

    var context = document.getElementById("canv").getContext("2d");

for (var k = 0; k < 4; k++) {
    var rect = new Recta();
    rect.drawIt();
}

在最后寫下面的代碼(在對象的定義之后)

    var context = document.getElementById("canv").getContext("2d");

    for (var k = 0; k < 4; k++) {
        var rect = new Recta();
        rect.drawIt();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM