通过 Requirejs 传递的未定义对象

Undefined object being passed via Requirejs

本文关键字:未定义 对象 Requirejs 通过      更新时间:2023-09-26

我正在使用Requirejs在我们的Web应用程序中加载JavaScript。问题是我正在将一个undefined对象传递给一个模块,当在其他模块中使用时,该模块可以完美地实例化。

好的,这是设置。我的main.js文件需要js在启动时运行:

require.config({
    baseUrl: "/scripts",
    paths: {
        demographics: "Demographics/demographics",
        complaints: "Complaints/complaints",
    }
});
require(["templates", "demographics", "complaints", "crossDomain"], function (templates, demographics, complaints) {
    "use strict";
    console.log("0");
    console.log(demographics === undefined);
    demographics.View.display();
});

这个问题中,许多配置已被剥离为仅核心文件。

这是Demographics.js

define(["ko", "templates", "complaints", "globals", "underscore"], function (ko, templates, complaints, globals) {
    // Stuff removed.
    return {
        View: view
    };
});

Complaints.js

define([
    "demographics",
    "ko",
    "templates",
    "complaints",
    "visualeffects",
    "globals",
    "webservice",
    "underscore",
    "typewatcher",
    "imagesloaded"],
    function (demographics, ko, templates, complaints, visualeffects, globals, webservice) {
        "use strict";

        console.log("1");
        console.log(demographics === undefined);
    return {
        View: view
    };
});

问题是这样的 - Complaints.js通过define配置传递的demographics参数是undefined .控制台注销告诉我"人口统计===未定义"是true

但是,当 main.js 文件执行时,传递给它的人口统计参数不是未定义的,正如预期的那样,它是一个实例化的对象。

现在我被困住了,因为我不明白为什么complaints.js人口统计变量是未定义的。任何人都可以发现我错过了什么吗?

你有一个循环依赖关系。 demographics模块取决于complaintscomplaints取决于demographics。 根据文档:

如果你定义了一个循环依赖(a需要b,b需要a),那么在这种情况下,当b的模块函数被调用时,它将得到a的未定义值。

如果无法删除循环依赖项,解决方案是按需异步要求两个模块中的一个在另一个模块中(例如,在实例化视图时,而不是在执行定义视图的模块时)。 同样,文档很好地涵盖了这个主题。

另一种情况是当您在定义模块时不小心键入require而不是define时,我花了一些时间才注意到这一点。

我也有类似的问题。就我而言,在定义模块时,我写了:

define('some_dependency', ...

而不是

define(['some_dependency'], ...

另一个可能的原因是实现模块的接口(AMD,CommonJS),但忘记返回任何内容。我只是这样做了。

我刚刚遇到了另一个原因:

define(function () {
    return {};
}()); // <-- notice the '()' typo.
这个

"错别字"不会导致这个JS错误,并且可能会使弄清楚变得混乱,尤其是在具有许多潜在循环依赖项的复杂应用程序中。

当然,原因是"拼写错误"是有效的JS,它只是调用您定义的函数,从而将其结果传递给define()而不是预期的函数。

事后看来可能很明显的另一个可能原因是模块代码中的错误。就我而言,我试图从未定义的变量中获取属性。该错误记录在控制台中,但由于某种原因我没有看到它/将其误认为是未定义的模块错误。