jquery - "use strict"; + jQuery.getScript() = 脚本无法导出到全局命名空间

标签 jquery global-variables getscript use-strict

假设我有以下脚本,名为 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 code eval("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:

来源:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode

解决方案不是使用 jQuery 加载脚本,而是将 script 元素附加到 DOM。请注意,您甚至不能使用 jQuery 来附加元素;它会自动使用 $.getScript()

关于jquery - "use strict"; + jQuery.getScript() = 脚本无法导出到全局命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12776405/

相关文章:

jquery - 在 FlexBox 中使用 ScrollTop 不起作用

javascript - 在 CSS 中使用 javascript

Android 在 Activity 之间传递变量

jquery - css 动画在脚本加载时被挂起

javascript - 关于 jQuery 的 getScript() 的问题

javascript - 使用 jQuery 进行字符串插值

javascript - 自下而上的 jQuery Masonry

javascript - 在Python中使用函数声明全局变量

function - 如何从函数内部为全局变量分配新值

javascript - 使用 $.getScript 回调函数加载脚本