在javascript类函数中调用函数?

时间:2014-03-03 13:39:15

标签: javascript class

我试图将属性和函数声明为特定的js类。但是当我尝试在函数内调用函数时(即使在声明后调用)它会抛出异常

未捕获TypeError:对象[object Object]没有方法'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 个答案:

答案 0 :(得分:2)

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

您可以更改

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

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

你还必须在绑定menuIn(对某个事件?)的地方做同样的事情。

答案 1 :(得分:1)

您的问题是this,它指向当前上下文(在运行时)而不是您的对象。 只需在SplashScreen中添加一个变量,如:

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

然后按如下方式调用它:

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