为什么 "use strict" 将命名空间内的函数分配中断到全局范围?
Why does "use strict" break function assignment inside namespace to global scope?
我有库代码做一个简单的函数分配。从全局范围访问此函数。
当我在文件开头添加 "use strict"
时,在分配给 a.b
.
时出现错误 TypeError: a is undefined
"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 是 undefined,所以你不能让b变成undefined
我有库代码做一个简单的函数分配。从全局范围访问此函数。
当我在文件开头添加 "use strict"
时,在分配给 a.b
.
TypeError: a is undefined
"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 是 undefined,所以你不能让b变成undefined