gpt4 book ai didi

javascript - IIFE 单例全局未定义,除非调用为 window.XYZ = IIFE()

转载 作者:行者123 更新时间:2023-11-27 23:48:29 31 4
gpt4 key购买 nike

为什么这个函数运行时没有用返回值初始化全局XYZ

"use strict";
XYZ = (function(){
var obj = {'a':1,'b':2,'c':3};
console.log("about to return:");
console.log(obj);
return obj;
})();
console.log(XYZ); // shows undefined

jsfiddle

奇怪的是,前两个 console.log 返回合理的输出,然后 Chrome 抛出 Uncaught ReferenceError: XYZ is not Defined

当显式使用 window.XYZ 时,效果很好:

"use strict";
window.XYZ = (function(){
var obj = {'a':1,'b':2,'c':3};
console.log("about to return:");
console.log(obj);
return obj;
})();
console.log(XYZ); // shows a:1, b:2, c:3

最佳答案

如果 "use strict;" 则两者都有效已移除。但不要这样做——继续阅读。

严格模式会阻止 XYZ = ...不再成为一个新的全局变量。

John Resig explains in his overview of strict mode :

An attempt to assign foo = "bar"; where foo hasn’t been defined will fail. Previously it would assign the value to the foo property of the global object (e.g. window.foo), now it just throws an exception. This is definitely going to catch some annoying bugs.

带有 window.XYZ = IIFE() 的代码在严格模式下工作,因为这里分配的是现有对象的属性, window

使用window.XYZ对于许多应用程序来说可能“足够好”,但您可能会遇到使用 window.XYZ 的平台(例如 Meteor)包管理器中的“短路”依赖管理。在这种情况下,可以在 IIFE 内部启用严格模式,但不能在页面级别启用。

要将严格模式与分配给新全局的单例 IIFE 结合使用,只需在 IIFE 内的第一行启用严格模式。

XYZ = (function() {
"use strict";
var obj = {
'a': 1,
'b': 2,
'c': 3
};
console.log("about to return:");
console.log(obj);
return obj;
})();
console.log(XYZ);

警告:“使用严格;”因为第二行没有启用严格模式:

不要这样做:

XYZ = 0;
"use strict";
XYZ = ...

您可以通过查看 this 来测试严格模式是否启用。在函数内 this没有明确设置。当严格模式为 true 时,this将是null未设置但严格模式为 false 时,this将是window

另请参阅:What does "use strict" do in JavaScript, and what is the reasoning behind it?

关于javascript - IIFE 单例全局未定义,除非调用为 window.XYZ = IIFE(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941401/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com