javascript - 为什么 "use strict"会破坏命名空间内的函数分配到全局作用域?

标签 javascript strict javascript-namespaces

我有库代码执行简单的函数分配。该函数是从全局范围访问的。

当我添加"use strict"时在文件的开头,我收到错误 TypeError: a is undefined ,分配给a.b .

"use strict"; /* Remove this and 'a' is defined */
(function() {
  var a = this;
  a.b = function() {
    document.getElementById('test').innerHTML = 'abc';
  };
})();
b();
<div id="test"></div>

考虑到var a,为什么我会收到此错误是在上一行声明的吗?

最佳答案

Global Leakage

There are a number of situations that could cause this to be bound to the global object. For example, if you forget to provide the new prefix when calling a constructor function, the constructor's this will be bound unexpectedly to the global object, so instead of initializing a new object, it will instead be silently tampering with global variables. In these situations, strict mode will instead bind this to undefined, which will cause the constructor to throw an exception instead, allowing the error to be detected much sooner.

所以你没有a作为this,但你的a未定义,所以你不能b未定义

关于javascript - 为什么 "use strict"会破坏命名空间内的函数分配到全局作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889261/

相关文章:

javascript - 函数的 this 值存储在哪里?

PHP 严格标准 : Only variables should be passed by reference//array_pop

javascript - 严格模式下可变类型的对象?

javascript - OOP,命名空间顶级方法中的私有(private)函数

typescript - 如何在 Typescript 中的两个不同文件中正确导入相同的命名空间

javascript - JavaScript 模块模式与其替代方案有什么区别?

javascript - 当fetch返回404时替换img url

javascript - jQuery ajax - 仅当所有重试失败时才触发失败回调函数

mysql - 如何全局启用 mysql 严格模式并让它保持打开状态?

javascript - 一次显示一张图像?