将函数放入类中

Putting functions into a class

本文关键字:函数      更新时间:2023-09-26

我想把多个函数放入一个类。这样我就可以用数组把它推出来。但由于一些错误,我仍然无法将函数推入数组。我的程序是在画布上创建一个动画鱼精灵。为了进行下一步,我想在画布上添加更多的鱼。

这是一个快速而简单的Fish "类"的例子。

示例:http://jsfiddle.net/m1erickson/jEznV/

Fish类就像模板一样被用来创建任意数量的Fish副本。

你像这样定义Fish类和属性:

// A Fish Class
function Fish(x,y,speedX,speedY,img){
    this.image=img;
    this.xPos=x;
    this.yPos=y;
    this.speedX=speedX||1;
    this.speedY=speedY||1;
}

你像这样定义Fish类的函数(称为方法):

// change the x/y position of this fish
Fish.prototype.move=function(){
    this.xPos+=this.speedX;
    this.yPos+=this.speedY;
};
// draw this fish on the canvas
Fish.prototype.draw=function(){
    context.drawImage(this.image,this.xPos,this.yPos);
};

你可以使用Fish类创建一个实际的Fish对象,如下所示:

// create another fish using the Fish class
var anotherFish=new Fish(20,40,2,1,img);

你可以把所有的鱼放到一个数组中:

// an array holding several instances of Fish objects
var fishes=[];
// create 3 new copies (instances) of Fish at random positions/speeds
for(var i=0;i<3;i++){
    var x=Math.random()*50-img.width;
    var y=i*img.height+25;
    var speedX=Math.random()*.25+.2;
    var speedY=.1;
    // create another fish using the Fish class
    var anotherFish=new Fish(x,y,speedX,speedY,img);
    // put this new fish into the fishes[] array
    fishes.push(anotherFish);
    // draw this new fish
    anotherFish.draw();
}

javascript类教程超出了Stackoverflow答案的范围,但这应该让你开始。

[添加图像预加载器代码]

// image loader
var imageURLs=[];  // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("FishStrip.png");
imageURLs.push("moreFish.png");
imageURLs.push("evenMoreFish.png");
loadAllImages(start);
function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}
function start(){
    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]
    // imgs[0] is FishStrip.png
    // imgs[1] is moreFish.png
    // imgs[2] is evenMoreFish.png
    // use the imgs[] to create your Fish instances now

}