Javascript在构造函数中调用构造函数

时间:2014-06-26 09:14:54

标签: javascript pixi.js

我正在与PixiJS合作,但我的问题非常笼统。我创建了一个构造函数(1),并在该构造函数(1)中调用另一个构造函数(2)。我现在需要从构造函数(1)访问构造函数(2)的一些方法,但我总是得到输出'无法读取属性'渲染器'未定义的'。我做错了什么?

调用构造函数1及其方法' animate':

stage3 = new site3();
requestAnimationFrame(stage3.animate);

构造函数1:

function site3() {
    this.fullstage = new fullscreenstage("intimg");

    this.snowfrontblur = new PIXI.BlurFilter();
    this.snowfrontblur.blurX = 5;
    this.snowfrontblur.blurY = 5;

    this.snowfront = SpriteFromImage("resources/img/snow.png",0,0,0.5,0.5);
    this.fullstage.stage.addChild(this.snowfront);

    this.snowfront.filters = [this.snowfrontblur];
}

site3.prototype.animate = function() {
    this.fullstage.renderer.render(this.fullstage.stage);
    requestAnimationFrame(this.animate);
};

构造函数2:

function fullscreenstage(cavansid){
    this.renderer = new PIXI.WebGLRenderer(ww, wh, null, true);
    document.getElementById(cavansid).appendChild(this.renderer.view);
    this.interactive = true;
    this.stage = new PIXI.Stage(0x000000, this.interactive);    
}

2 个答案:

答案 0 :(得分:1)

您面临的问题与JS如何将上下文绑定到函数有关:它是一种ad-hoc绑定。上下文(由this关键字表示)可以根据调用函数对象的方式和位置而有所不同 在这个声明中:

requestAnimationFrame(stage3.animate);

您将对animate函数对象的引用传递给requestAnimationFrame,但这样做时,该函数会丢失其上下文,因此当您在requestAnimationFrame内调用该函数时,{{ 1}}关键字不会绑定到this。最简单的解决方法是传递整个对象:

stage3

在这种情况下,requestAnimationFrame(stage3); //in requestAnimationFrame: function requestAnimationFrame(instance) { instance.animate(); } 函数中的this.fullstage.renderer.render(this.fullstage.stage);将正确解析。

另一个选择是以更永久的方式将上下文绑定到函数:

animate

我将添加一些指向JS的上下文绑定详细信息的链接,从以下开始:

this answer of mine请务必查看底部的链接

JavaScript "this" keyword and Closure Compiler warnings

答案 1 :(得分:0)

我通过在site3()的开头创建对自己对象的引用并将animate方法实现到构造函数中来解决它:

function site3() {
    var that = this; //creating the reference
    this.fullstage = new fullscreenstage("intimg");

    this.snowfrontblur = new PIXI.BlurFilter();
    this.snowfrontblur.blurX = 5;
    this.snowfrontblur.blurY = 5;

    this.snowfront = SpriteFromImage("resources/img/snow.png",0,0,0.5,0.5);
    this.fullstage.stage.addChild(this.snowfront);

    this.snowfront.filters = [this.snowfrontblur];

    this.animate = function(){
        that.fullstage.renderer.render(that.fullstage.stage);
        requestAnimationFrame(that.animate);    
    }
}
相关问题