对象内的函数无法在javascript中访问该对象

时间:2014-03-05 09:42:58

标签: javascript jquery object canvas requestanimationframe

我试图通过一组点移动cicle,例如在水平或垂直方向的管道内

我在对象中使用函数并尝试调用同一对象的另一个函数。

var ParticleGen = function() {
    this.pipeBegin = points[pipeIndex];
    this.pipeEnds = points[pipeIndex + 1];
    this.begin = function(){
        var pipeBegin = points[pipeIndex];
        var pipeEnds = points[pipeIndex + 1];
        nx = pipeBegin.x;
        ny = pipeBegin.y;
        if(pipeBegin.x == pipeEnds.x && pipeBegin.y >= pipeEnds.y){
            if(ny > pipeEnds.y) {
                ctx.clearRect(0, 0, w, h);
                drawCircle(nx, ny);
                ny--;
                nx = nx;
            }else if(ny == pipeEnds.y){
                cancelAnimationFrame(animloop);
                this.callBegin();
            }   
            requestAnimFrame(animloop);
        }
        animloop();
    }
    this.callBegin = function(){
        if(pipeIndex <= 3){
            pipeIndex++;
        }
        this.begin();
    }
};

但它会引发错误。

Uncaught TypeError: Object [object global] has no method 'callBegin' 

可以看到代码段here

谢谢,

2 个答案:

答案 0 :(得分:0)

jsfiddle中的代码与您发布的代码不同。

在jsfiddle,你有:

    if (pipeBegin.x == pipeEnds.x && pipeBegin.y >= pipeEnds.y) {
        // endpoint y greater than start point y moving upwards
        function animloop() {
            if (ny > pipeEnds.y) {
                console.log(nx + " : nx, ny : " + ny)
                ctx.clearRect(0, 0, w, h);
                drawCircle(nx, ny);
                ny--;
                nx = nx;
            } else if (ny == pipeEnds.y) {
                console.log(this)
                cancelAnimationFrame(animloop);
                this.callBegin();
            }
            requestAnimFrame(animloop);
        }
        animloop();

    }

您在函数this.callBegin()中使用animloop,然后this将引用全局对象window

您可以将animloop();更改为animloop.call(this);animloop.apply(this);以约束右this

答案 1 :(得分:0)

您正在调用的函数this.callBegin不是您认为的函数:当您拨打电话时,您在另一个函数(animloopanimloop1等)内(第63行)分别为78)。在这些函数中,the scope is changedthis关键字会引用函数animloop(不是ParticleGenwindow)。 animloop没有属性callBegin(函数或其他)。

您应首先“保存”ParticleGen范围,以便在子功能中使用它:

var ParticleGen = function() {

    var pg = this;

    // etc

    function animloop() {

        // etc

        pg.callBegin();

    }
}

更新的工作小提琴:http://jsfiddle.net/PZCpf/2/