8Observer8 Posted May 7, 2017 Share Posted May 7, 2017 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(); } Quote Link to comment Share on other sites More sharing options...
labrat.mobi Posted May 7, 2017 Share Posted May 7, 2017 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(); })); 8Observer8 1 Quote Link to comment Share on other sites More sharing options...
8Observer8 Posted May 7, 2017 Author Share Posted May 7, 2017 Thank you very much! I will study the documentation for the links gradually. I like the second solution with the arrow function. Quote Link to comment Share on other sites More sharing options...
tywang2006 Posted May 8, 2017 Share Posted May 8, 2017 PIXI.loader.add("./images/chapter01/pixie96x48.png") .load(this.setup.bind(this); when you code typescript, it should be same as javascript to bind your reference 8Observer8 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.