JavaScript - 原型(prototype)方法未定义

标签 javascript object prototype

我只是不明白为什么我的绘图函数未定义。这和原型(prototype)有关系。本质上,我希望创建的每个新对象都有自己的 x、y、dx 和 dy,以便我可以使用对象创建多个弹跳球,并且我认为使用原型(prototype)为每个对象创建方法将是一种有效的方法。

document.addEventListener("DOMContentLoaded", function(event){
var canvas,
    context,
    altezza,
    larghezza,
    x = 100,
    y = 100,
    raggio = 25,
    dx = 5,
    dy = 5,
    immagine,
    ballTest;

    window.onload = init;

    //Assegniamo a canvas l'elemento HTML canvas 
    canvas = document.getElementById("campo");
    //Assegniamo a context un oggetto che contiene tutti i metodi per disegnare
    context = canvas.getContext("2d");
    //Assegniamo a "dy" una velocità iniziale di 0.1 che verrà incrementato nel tempo
    dy = 0.1;
    //Assegniamo a immagine l'immagine della sfera
    immagine = new Image;
    immagine.src = "tBall.png";
    //Assegniamo alle variabli altezza e larghezza le dimensioni del campo
    larghezza = window.screen.availWidth - 40;
    altezza = window.screen.availHeight - 120;

    function Entity(x, y, raggio){
        this.x = x;
        this.y = y;
        this.raggio = raggio;
        draw();
    }

    Entity.prototype.draw = function(){
        context.clearRect(0, 0, context.canvas.width, context.canvas,length);
        context.drawImage(immagine, x, y, raggio, raggio);
    };

    //MIGHT NEED TO PUT THIS.X AND THIS.Y
    Entity.prototype.move = function(dx, dy){
        if(this.x < -10 || this.x > larghezza - 20){
            dx *= -1;
        }
        if(this.y < 20 || this.y > altezza - 40){
            dy *= -1;
        }

        this.x += dx;
        this.y += dy;
    };

    function init(){
        //Assegniamo a canvas l'elemento HTML canvas 
        canvas = document.getElementById("campo");
        //Assegniamo a context un oggetto che contiene tutti i metodi per disegnare
        context = canvas.getContext("2d");
        //Settiamo le dimensioni del campo di canvas
        context.canvas.width = larghezza;
        context.canvas.height = altezza;
        //Inizializziamo l'entità
        ballTest = new Entity(100, 100, 25);
        setInterval(ballTest.move.bind(dx, dy), 10);
    }
});

错误: Uncaught ReferenceError :未定义绘制

最佳答案

draw 函数位于 Entity 的原型(prototype)中,因此在 Entity 类中,您必须以 this.draw 的形式访问它().

function Entity(x, y, raggio){
        this.x = x;
        this.y = y;
        this.raggio = raggio;
        this.draw();
    }

关于JavaScript - 原型(prototype)方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133878/

相关文章:

javascript - Sencha 触摸 2 : Making changes to framework source

javascript - 当我使用多个 jQuery change() 方法调用我的函数时,如何避免多次调用它?

frameworks - Web框架编程思维

javascript - 使用 for 循环方法打印/记录数组中的对象

javascript - 如果类和对象之间没有区别,为什么这段代码不起作用?

javascript - 在对象类声明中设置 javascript 原型(prototype)函数

javascript - Firebase - JS 查询 - 获取一个节点,其中子值具有值为 xxx 的子节点

javascript 函数中的 C# 参数

java - 创建一个参数是类和通用 ArrayList 的方法

javascript - 检查对象是否具有用户定义的原型(prototype)?