使用JavaScript函数作为;“类”:我做错了什么?
到目前为止,我的JavaScript“类”如下:使用JavaScript函数作为;“类”:我做错了什么?,javascript,Javascript,到目前为止,我的JavaScript“类”如下: 函数蛇(C,C_h,C_w) { this.linkSize=10;//蛇形单位的大小,以像素为单位 /*在实例化时,蛇的方向是向下的,并且有一个链接*/ this.dy=this.linkSize; 该值为0.dx=0; this.link=C.rect(C_h/2,C_w/2,this.linkSize,this.linkSize); this.link.attr(“fill”,“#d7a900”); this.body=[link]; /*
函数蛇(C,C_h,C_w)
{
this.linkSize=10;//蛇形单位的大小,以像素为单位
/*在实例化时,蛇的方向是向下的,并且有一个链接*/
this.dy=this.linkSize;
该值为0.dx=0;
this.link=C.rect(C_h/2,C_w/2,this.linkSize,this.linkSize);
this.link.attr(“fill”,“#d7a900”);
this.body=[link];
/*事件侦听器,用于更改事件的方向
键盘上有箭头键的蛇
*/
this.redirect=函数(dirnum)
{
开关(dirnum)
{
/*
dirnum对应于
1--->对
2--->向下
3--->左
4--->向上
*/
案例1:
this.dx=this.linkSize;
这是0.dy=0;
打破
案例2:
该值为0.dx=0;
this.dy=this.linkSize;
打破
案例3:
this.dx=-this.linkSize;
这是0.dy=0;
打破
案例4:
this.dx=-this.linkSize;
这是0.dy=0;
打破
默认情况永远不会发生
打破
}
}
this.move=函数()
{
/*
/////
*/
var temp=主体[0];
正文[0]。翻译(this.dx,this.dy);
对于(变量i=1,j=body.length;i
我的Google Chrome控制台中报告了两个问题:
- 未捕获引用错误:未定义链接(在
行上)李>this.link.attr(“fill”,“d7a900”)
(每当我按箭头键时)未捕获类型错误:未定义不是函数
有没有人对这些问题发生的原因有所了解?我是否正确使用了
this.
关键字?未捕获引用错误:未定义链接
表示调用C.rect()
返回未定义
或空
“未捕获类型错误:未定义不是函数(每当我按箭头键时)”
代码中没有可见的事件处理,但这可能只是一个后续错误
三次检查(使用console.log
)是否正确地将C
传递到函数中,以及C.rect()
的返回值实际是什么。和C
是什么?如果它是未定义的,那么link
是未定义的,C.rect
究竟返回什么?C是拉斐尔对象()
function snake(C, C_h, C_w)
{
this.linkSize = 10; // size of a snake unit, in pixels
/* On instantiation, the snake direction is down and has 1 link */
this.dy = this.linkSize;
this.dx = 0;
this.link = C.rect(C_h/2, C_w/2, this.linkSize, this.linkSize);
this.link.attr("fill", "#d7a900");
this.body = [link];
/* Event listener for changing the direction of the
snake with arrow keys on the keyboard
*/
this.redirect = function(dirnum)
{
switch (dirnum)
{
/*
dirnum corresponds to
1 ---> right
2 ---> down
3 ---> left
4 ---> up
*/
case 1:
this.dx = this.linkSize;
this.dy = 0;
break;
case 2:
this.dx = 0;
this.dy = this.linkSize;
break;
case 3:
this.dx = -this.linkSize;
this.dy = 0;
break;
case 4:
this.dx = -this.linkSize;
this.dy = 0;
break;
default: // never happens
break;
}
}
this.move = function()
{
/*
/////
*/
var temp = body[0];
body[0].translate(this.dx, this.dy);
for (var i = 1, j = body.length; i < j; ++i)
{
body[i] = temp;
temp = body[i];
}
}
setInterval(this.move());
}