0

我似乎遇到了 JavaScript 中名称间距的问题。

我已将我的 javascriptobjects分成单独的文件。

每个文件都以命名空间定义开始:

var MySystem = MySystem || {};

如果我包含该对象,该对象调用它之后包含在文件中的对象的某些方法 - 我得到 TypeError 说给定对象不存在。

我遇到的问题示例:

文件 1 Url.js(首先包含在 html 文档中):

var MySystem = MySystem || {};

MySystem.Url = {

    objHelper : MySystem.Helper,

    init : function() {

        "use strict"

        if (this.objHelper.isEmpty('string')) {

            throw new Error('The string is empty');

        }

    }

}

文件 2 Helper.js(包含在 html 文档中的第二个):

var MySystem = MySystem || {};

MySystem.Helper = {

    isEmpty : function(thisValue) {

        "use strict"

        return (
            typeof thisValue === 'undefined' ||
            thisValue === false ||
            thisValue === null ||
            thisValue === ''
        );

    }

}

当使用我调用时,MySystem.Url.init();我得到:

TypeError: this.objHelper is undefined  
if (this.objHelper.isEmpty('string')) {

当我颠倒包含文件的顺序时 - 一切正常。

这显然是一个非常简单的例子,但我的系统包含更多objects——所有这些都在它们自己的单独文件中。

这个问题的最佳解决方法是什么?

4

1 回答 1

0

你试图重新发明模块系统。使用 require.js http://requirejs.org/

于 2018-01-19T06:18:19.663 回答