使用JavaScript函数作为"类":我在这里做错了什么?

时间:2014-05-30 20:25:50

标签: javascript

到目前为止,这是我的JavaScript“课程”:

    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());
    }

我在谷歌Chrome控制台中报告了2个问题:

  • 未捕获的ReferenceError:链接未定义(在this.link.attr("fill", "#d7a900");行上)。
  • Uncaught TypeError: undefined is not a function(每当我按箭头键时)

有没有人对这些问题发生的原因有所了解?我正确使用this.关键字吗?

1 个答案:

答案 0 :(得分:1)

Uncaught ReferenceError: link is not defined表示对C.rect()的调用会返回undefinednull

Uncaught TypeError: undefined is not a function(每当我按箭头键时)”

您的代码中没有可见的事件处理,但这可能只是一个后续错误。

三次检查(使用console.logC正确传递给函数以及C.rect()的返回值实际是什么。