admin管理员组文章数量:1356836
I wrote a script like that:
NS.load = function(src) {
var script = document.createElement("script").setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);
}
It loads files but I can't reach functions and variables defiened in other files.
//js/main.js
var qux = {name: "name"};
NS.load("js/foo.js");
//js/foo.js
alert(qux.name); //undefined variable
But if I define qux like this:
window.qux = {name: "name"};
I can reach qux variable in other modules. As far as I know all globals are already a member of window object. So why I have to define variables like this. Could you offer another method?
Thanks.
I wrote a script like that:
NS.load = function(src) {
var script = document.createElement("script").setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);
}
It loads files but I can't reach functions and variables defiened in other files.
//js/main.js
var qux = {name: "name"};
NS.load("js/foo.js");
//js/foo.js
alert(qux.name); //undefined variable
But if I define qux like this:
window.qux = {name: "name"};
I can reach qux variable in other modules. As far as I know all globals are already a member of window object. So why I have to define variables like this. Could you offer another method?
Thanks.
Share Improve this question edited Jul 8, 2017 at 20:23 Nathan Wailes 12.4k10 gold badges75 silver badges114 bronze badges asked Jan 11, 2010 at 12:35 jsonxjsonx 1,0893 gold badges14 silver badges21 bronze badges1 Answer
Reset to default 7It looks like you tried to shortcut your code by calling createElement
and setAttribute
all on 1 line, but setAttribute
doesn't return anything, so you can't go calling appendChild
on it's return value, because there is none.This will fix it:
NS.load = function(src) {
var script = document.createElement("script");
script.setAttribute("src", src)
document.getElementsByTagName("head")[0].appendChild(script);
}
Edit:
What sort of environment are you running your code in? Is something happening cross-site or are you defining qux inside of another function? The following works for me, running the files via 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>
foo.js:
alert(qux.name);
I get an alert with "name" when the page loads.
本文标签:
版权声明:本文标题:Why isn't my JavaScript function able to access global-scope functionsvariables defined in my other .js files? - Stack O 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743957830a2568457.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论