2014-03-03 169 views
0

我想向特定的js类声明属性和函数。但是,当我尝试调用一个函数(即使宣布之后调用)的内部函数,它抛出一个异常JavaScript类函数内部调用函数?

遗漏的类型错误:对象的翻译:有没有方法“addButtonEventListeners

我的代码所示:SplashScene.js

var anim1, background; 
var SplashScene; 

function SplashScreen(SceneContainer) 
{ 
this.name = "SplashScreen"; 
this.loadScreen = function() 
{ 

    background = new createjs.Shape(); 
    background.graphics.beginBitmapFill(loader.getResult("gameLoopSplash")).drawRect(0,0,w,h); 
    SplashScene = new createjs.Container(); 

    anim1 = new createjs.Sprite(buttonData, "playIdle"); 
    anim1.framerate = 30; 
    anim1.x = 260; 
    anim1.y = 22; 
    SplashScene.alpha = 0; 

    SplashScene.addChild(background); 
    SplashScene.addChild(anim1); 
} 

this.addButtonEventListeners = function() 
{ 
    console.log("addButtonEventListeners SplashScreen"); 
} 

this.menuIn = function() 
{ 
    console.log("menuIn SplashScreen"); 
    stage.addChild(SplashScene); 
    var tween = createjs.Tween.get(SplashScene).to({y : 0, x : 0, alpha : 1}, 5000).call(this.menuInCompleted); 
    var splashTimer = window.setTimeout(function(){menuOut("MainScreen", false)},15000); 

} 

this.menuInCompleted = function() 
{ 
    console.log("menuInCompleted SplashScreen"); 
    this.addButtonEventListeners(); 
} 
} 

有人可以告诉我我该怎么做?

回答

2

问题是setTimeout回调中的上下文()是window,而不是您的对象。

您可以更改

var splashTimer = window.setTimeout(function(){menuOut("MainScreen", false)},15000); 

var splashTimer = window.setTimeout(
    (function(){menuOut("MainScreen", false)}).bind(this) 
,15000); 

,你也必须做同样的,你绑定menuIn(一个事件?)。

+0

菜单吐温是工作,但菜单不出来。我做了你所说的。但它仍然不起作用。 – starrystar

1

你的问题是this,它指向当前上下文(在运行时)而不是你的对象的上下文。 就在闪屏添加一个变量,如:

var self=this; //keeping the context of SplashScreen 

然后调用它,如下所示:

this.menuInCompleted = function() 
{ 
    console.log("menuInCompleted SplashScreen"); 
    self.addButtonEventListeners(); 
} 
+0

ıt工作:)非常感谢你:) – starrystar