我有库代码执行简单的函数分配。该函数是从全局范围访问的。
当我添加"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/