我一直在寻找与我相似的其他问题,但我似乎无法找到答案。
我所遇到的错误也在标题中:
Uncaught TypeError: self.Rotate() is not a function
以下是发生这种情况的完整代码:
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);
};
在Setup函数结束时,我尝试调用Rotate函数,这就是它失败的地方。
答案 0 :(得分:1)
在Card.prototype.Setup
内,以及之后添加到Card.prototype
的其他方法,self
为window.self
,因为var
是私有的,不属于属性您的构造函数从其原型Object继承的。将self
更改为this
或Card
(如果您更喜欢要绑定的上下文),请查找您所查找的上下文。
答案 1 :(得分:1)
我发现此代码可以防止您遇到的addChild问题。请查看代码中的注释以获得解释。
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);
};