2

因此,在加载 fileList 数组中的第一个文件时正确调用的函数 fileLoaded 中,它尝试调用 this.loadAnother() 但 Firefox 坚持:

TypeError: this.loadAnother is not a function

为什么它坚持它不是一个功能?它从 loadProjectSource() 中被正确调用,但试图加载下一个文件,它不是一个函数。此外,调试“this”会产生奇怪的结果,这让我相信这是罪魁祸首。我不是 Javascript 专家,但我从未见过这种行为。它与类创建有关吗?如果是这样,为什么 loadProjectSource() 的第一次调用有效?

var ScriptLoader = Class.extend({ // Want to add functionality to this to allow PHP or inline loading...perhaps later
    init: function () {
        this.totalEngineToLoad = 0;
        this.totalEntitiesToLoad = 0;
        this.totalScenesToLoad = 0;
        this.totalLoaded = 0;
        this.entitiesToLoad = [0, 0, 0];
        this.fileList = ['./js/engine/Entity.js', './js/engine/Scene.js'];
        this.preload;
    },
    loadProjectSource: function (directory) {
        if(this.preload != null) {
            this.preload.close();
        }
        this.preload = new createjs.LoadQueue();
        this.preload.addEventListener("fileload", this.fileLoaded);
        this.preload.addEventListener("error", this.fileError);
        this.preload.setMaxConnections(5);
        this.loadAnother();
    },
    loadAnother: function () {
        var myItem = this.fileList.shift();
        if(this.fileList.length != 0) {
            this.preload.loadFile(myItem);
        }
    },
    fileLoaded: function (e) {
        debug('Loaded ' + e.item.src);
        debug(this.fileList);
    },
    fileError: function (e) {
        debug('Error ' + e.item.src);
    }
}
4

3 回答 3

0

这是因为上下文绑定。

在这一行:

this.preload.addEventListener("fileload", this.fileLoaded);

回调函数中的上下文this将是window对象,而不是您的类实例。在现代浏览器中,您可以这样修复它:

this.preload.addEventListener("fileload", this.fileLoaded.bind(this));

在较旧的浏览器中,您需要这样的东西:

var self = this;
this.preload.addEventListener("fileload", function(){
    self.fileLoaded();
});

与下一行相同。

于 2013-03-26T16:50:02.767 回答
0

JavaScript 中的类很奇怪,至少在我的经验中,那里很麻烦。在您的 ScriptLoader 类中,尝试执行以下操作(您可能必须更改它以适应您的类的工作方式 - 我不使用它们,反正就是这样)

SL = this;

然后在你的 loadProjectSource 函数中,改变

this.loadAnother();

SL.loadAnother();

只是一个想法!

于 2013-03-26T16:50:57.783 回答
0

this关键字的值取决于函数的调用方式——事件处理程序不知道您希望它成为您的 ScriptLoader 实例。

要获得正确的上下文,您要么需要bind

this.preload.addEventListener("fileload", this.fileLoaded.bind(this));

或使用匿名函数作为在实例上显式调用实际方法的处理程序:

var that = this;
this.preload.addEventListener("fileload", function(){
    // while "this" points to something indetermined, "that" is the instance
    that.fileLoaded();
});

由于 TypeError 是“ this.loadAnother is not a function ”,并且您尝试调用的唯一地方是,因此在传递给未在正确上下文中调用它的东西时loadProjectSource,您似乎遇到了类似的问题。loadProjectSource

于 2013-03-26T16:51:08.330 回答