为什么我的JavaScript函数不能访问我的其他.js文件中定义的全局范围函数/变量?

jso*_*onx 2 javascript

我写了一个这样的脚本:

NS.load = function(src) {
    var script = document.createElement("script").setAttribute("src", src);
    document.getElementsByTagName("head")[0].appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)

它加载文件,但我无法到达其他文件中的功能和变量.

//js/main.js
var qux = {name: "name"};
NS.load("js/foo.js");

//js/foo.js
alert(qux.name); //undefined variable
Run Code Online (Sandbox Code Playgroud)

但如果我像这样定义qux:

window.qux = {name: "name"};
Run Code Online (Sandbox Code Playgroud)

我可以在其他模块中访问qux变量.据我所知,所有全局变量都已经是window对象的成员.那么为什么我必须定义这样的变量.你能提供另一种方法吗?

谢谢.

Lan*_*don 7

看起来你试图通过调用createElementsetAttribute 所有1行来快捷你的代码,但setAttribute不返回任何东西,所以你不能去调用appendChild它的返回值,因为没有.这将解决它:

NS.load = function(src) {
    var script = document.createElement("script");
    script.setAttribute("src", src)
    document.getElementsByTagName("head")[0].appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

您运行代码的环境是什么?是跨站点发生的事情还是你在另一个函数中定义qux?以下适用于我,通过http://localhost/test.html运行文件

<html>
<head>
    <script type="text/javascript">
        load = function(src) {
            var script = document.createElement("script");
            script.setAttribute("src", src);
            document.getElementsByTagName("head")[0].appendChild(script);
        }
        var qux = {name: "name"};
        load("foo.js");
    </script>
</head>
<body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

foo.js:

alert(qux.name);
Run Code Online (Sandbox Code Playgroud)

当页面加载时,我收到带有"名称"的警报.