javascript - 在javascript类函数中调用函数?

标签 javascript class

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

未捕获类型错误:对象 [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();
}
}

谁能告诉我该怎么做?

最佳答案

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

你可以改变

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

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

并且您还必须在绑定(bind) menuIn (到事件?)时执行相同的操作。

关于javascript - 在javascript类函数中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22148286/

相关文章:

javascript - 日历时间表

javascript - 添加 data-ajax ="false"后退按钮不起作用

c++ - 类中的错误二维 vector 类初始化

javascript - 在 JS OOP 中创建一个类

javascript - 使用 VueJS、VuelidateJS 和 NodeJS/Express 时的项目结构

javascript - Node 需要目录而不是特定文件

javascript - 单击进入 ace 编辑器时防止模态窗口向上滚动

ruby - 如何在 Ruby 模块上调用 #new 来实例化其类之一?

Java-如何从同一个包中的类获取私有(private)数据

c++ - Qt 4 C++ 在使用 3 个相互使用的类时出错,错误 : field `m_Employer' has incomplete type