将函数放入类中
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
}
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jquery点击函数select&取消选择
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- Node.js v6.2.0类扩展不是函数错误
- 比较从函数和生成的日期对象
- jQuery中是否内置了任何字符串格式化函数
- 当js函数's已执行