假设我有以下脚本,名为 include_strict.js
。执行后我应该有 window.global1
定义:
"use strict";
var globalVar = {};
alert(typeof window.globalVar);
但是如果我将它从 JavaScript block 中包含
$.getScript("include_strict.js");
警报显示 undefined
。为什么?这是怎么回事?
仅供引用,如果我使用脚本标记包含文件,则不会发生这种情况:
<script type="text/javascript" src="include_strict.js"></script>
在这里,我看到了预期的警报,object
。如果我删除 "use strict";
,然后都是 jQuery.getScript()
和<script>;
具有与显示 object
相同的效果.
我创建了一个示例 ( https://docs.google.com/file/d/0B-XXu97sL1Ckb0x0OHptTmVMY00/edit ) 来演示这一点。
最佳答案
它使用$.getScript()
,它使用eval
来执行严格模式下无法修改全局范围的脚本:
Second,
eval
of strict mode code does not introduce new variables into the surrounding scope. In normal codeeval("var x;")
introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable:
解决方案不是使用 jQuery 加载脚本,而是将 script
元素附加到 DOM。请注意,您甚至不能使用 jQuery 来附加元素;它会自动使用 $.getScript()
。
关于jquery - "use strict"; + jQuery.getScript() = 脚本无法导出到全局命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12776405/