Jump to content

this.stage is undefined


8Observer8
 Share

Recommended Posts

Hello,

I begin to study Pixi.js and TypeScript. This log shows "undefined" on line 34:

// Add the sprite to the stage
console.log(this.stage);

Code:

/// <reference path="./libs/pixi.js.d.ts" />

class Game
{
    private stage: PIXI.Container;
    private renderer: PIXI.WebGLRenderer | PIXI.CanvasRenderer;

    public constructor()
    {
        // Create the stage and renderer
        this.stage = new PIXI.Container();
        this.renderer = PIXI.autoDetectRenderer(256, 256);
        document.body.appendChild(this.renderer.view);
    }

    public run() : void
    {
        // User Pixi's build-in `loader` object to load an image
        PIXI.loader
            .add("./images/chapter01/pixie96x48.png")
            .load(this.setup);
    }

    // This `setup` function will run when the image has loaded
    private setup(): void
    {
        // Create the sprite from the texture
        let pixie = new PIXI.Sprite(
            PIXI.loader.resources["./images/chapter01/pixie96x48.png"].texture
        );

        // Add the sprite to the stage
        console.log(this.stage);
        this.stage.addChild(pixie);

        // Render the stage
        this.renderer.render(this.stage);
    }
}

window.onload = () =>
{
    let game = new Game();
    game.run();
}

 

Link to comment
Share on other sites

2 hours ago, 8Observer8 said:

This log shows "undefined" on line 34:

because, this keyword is locked inside setup function. It has no idea what `stage` variable is. More info here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this 

You can fix this by using `bind` function https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

public run() : void
{
	this.setup = this.setup.bind(this);
	
    // User Pixi's build-in `loader` object to load an image
    PIXI.loader
        .add("./images/chapter01/pixie96x48.png")
        .load(this.setup);
}

or use arrow function,

PIXI.loader
    .add("./images/chapter01/pixie96x48.png")
    .load(() => {
    	this.setup();
    }));

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...