Dries Dries - 2 months ago 9
Javascript Question

self.Rotate() is not a function in prototype

I've been looking at the other questions that are similar to mine, but I can't seem to find an answer.

The error that I'm having is in the title as well:

Uncaught TypeError: self.Rotate() is not a function


Here's the full code where this happens:

var Card = function(renderer, stage) {
var self = this;

self.name = "None";
self.health = 5;

self.renderer = renderer;
self.stage = stage;

self.sprite = null;

PIXI.loader.add("FirePlace/GW2-Logo.jpg").load(self.Setup);
};

Card.prototype.Setup = function() {
self.sprite = new PIXI.Sprite(PIXI.loader.resources["FirePlace/GW2-Logo.jpg"].texture);
console.log(self.stage);
self.stage.addChild(self.sprite);
console.log("Sprite loaded");
self.renderer.render(self.stage);
self.Rotate();
};

Card.prototype.SetName = function(name) {
self.name = name;
};

Card.prototype.Rotate = function() {
requestAnimationFrame(self.Rotate);

if (self.sprite === null)
console.log("Sprite is null");

if (self.sprite !== null && self.sprite.rotation <= 1.5708)
self.sprite.rotation += 0.03;

self.renderer.render(self.stage);
};


At the end of the Setup function I try to call the Rotate function and this is where it fails.

Answer

I have found that this code prevents the addChild problem that you had. Look at the comments in the code for explanation.

var Card = function(renderer, stage) {
    var self = this;

    self.name = "None";
    self.health = 5;

    self.renderer = renderer;
    self.stage = stage;

    self.sprite = null;
    var x = function(){
        self.Setup.apply(self,arguments); 
    }
    PIXI.loader.add("FirePlace/GW2-Logo.jpg").load(x); // origionally: PIXI.loader.add("FirePlace/GW2-Logo.jpg").load(self.Setup);
    // self would not be defined in whatever other context it is used in when it is called. All I had to do was wrap it in a function and it was fixed
};

Card.prototype.Setup = function() {
    var self = this;
    self.sprite = new PIXI.Sprite(PIXI.loader.resources["FirePlace/GW2-Logo.jpg"].texture);
    console.log("Stage is:",self.stage); // Now stage is defined since I wrapped this function in another function.
    self.stage.addChild(self.sprite);
    console.log("Sprite loaded");
    self.renderer.render(self.stage);
    self.Rotate();
};

Card.prototype.SetName = function(name) {
    var self = this; // I also defined self = this in every single function :D
    self.name = name;
};

Card.prototype.Rotate = function() {
    var self = this;
    var x = function(){
        if (self.sprite === null)
        console.log("Sprite is null");

        if (self.sprite !== null && self.sprite.rotation <= 1.5708) 
            self.sprite.rotation += 0.03;

        self.renderer.render(self.stage);
        window.requestAnimationFrame(x);
    }; // Same goes for this one. 
    window.requestAnimationFrame(x);


};
Comments