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

构造函数中的Javascript调用构造函数,javascript,pixi.js,Javascript,Pixi.js,我正在和你一起工作,但我的问题很笼统。我创建了一个构造函数(1),并在该构造函数(1)中调用另一个构造函数(2)。我现在需要从构造函数(1)访问构造函数(2)的一些方法,但我总是得到输出“无法读取未定义的属性”renderer“。我做错了什么 调用构造函数1及其方法“animate”: stage3 = new site3(); requestAnimationFrame(stage3.animate); 建造商1: function site3() { this.fullstage

我正在和你一起工作,但我的问题很笼统。我创建了一个构造函数(1),并在该构造函数(1)中调用另一个构造函数(2)。我现在需要从构造函数(1)访问构造函数(2)的一些方法,但我总是得到输出“无法读取未定义的属性”renderer“。我做错了什么

调用构造函数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);    
}

您所面临的问题与JS如何将上下文绑定到函数有关:它是一个临时绑定。上下文(由
this
关键字表示)可能因调用函数对象的方式和位置而异。
在本声明中:

requestAnimationFrame(stage3.animate);
您将对
animate
函数对象的引用传递给
requestAnimationFrame
,但这样做时,函数将失去其上下文,因此当您在
requestAnimationFrame
中调用该函数时,
this
关键字将不会绑定到
stage3
。最简单的修复方法是传递整个对象:

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

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

site3.animate.bind(site3);
随着时间的推移,我将添加一些关于JS上下文绑定细节的链接,首先是:

确保检查底部的链接


我通过在
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);    
    }
}

在构造函数中定义方法是一个糟糕的想法。。。它实际上违背了构造函数的全部观点:它为每个实例创建了一个新的函数对象。您还可以在函数中构造一个对象文本并返回它。如果省略带有此函数的
new
关键字会使上下文变得混乱,那就更好了