问题描述
每次有人提到对 undefined
进行测试时, undefined
不是关键字所以,所以意外将 undefined
设置为的人null
,这是为了避免假设 undefined
未被覆盖。但是如果他们这样做了,这个bug就不会被发现了,我也看不出它有多好。
I found one example of someone who accidentally set undefined
to null
, and this was given as a reason to avoid assuming that undefined
isn't overwritten. But if they'd done that, the bug would have gone undetected, and I fail to see how that's better.
在C ++中,每个人都清楚地知道说这是合法的 #define true false
,但没有人建议你避免 true
并使用 0 == 0
而不是。你只是假设没有人会成为那么大的混蛋,如果他们这样做,再也不会相信他们的代码了。
In C++ everyone is well aware that it's legal to say #define true false
, but nobody ever advises you avoid true
and use 0 == 0
instead. You just assume that nobody would ever be a big enough jerk to do that, and if they do, never trust their code again.
这是否真的咬了别人的某个地方否则分配给 undefined
(故意)并且它破坏了你的代码,或者这更像是一个假想的威胁?我愿意冒险让我的代码更具可读性。这是一个非常糟糕的主意吗?
Has this ever actually bitten somebody where someone else assigned to undefined
(on purpose) and it broke your code, or is this more of a hypothetical threat? I'm willing to take my chances to make my code marginally more readable. Is this a really bad idea?
重申一下,我不询问如何防止重新分配未定义。我已经看过那些已经写过100次的技巧了。我问不使用这些技巧是多么危险。
To reiterate, I am not asking for how to protect against reassigned undefined. I've seen those tricks written 100 times already. I'm asking how dangerous it is to not use those tricks.
推荐答案
不,我从来没有。这主要是因为我在现代浏览器上开发,这些浏览器大多数符合ECMAScript 5。 ES5标准规定 undefined
现在只读。如果您使用严格模式(您应该),如果您不小心尝试修改它将会引发错误。
No, I never have. This is mostly because I develop on modern browsers, which are mostly ECMAScript 5 compliant. The ES5 standard dictates that undefined
is now readonly. If you use strict mode (you should), an error will be thrown if you accidentally try to modify it.
undefined = 5;
alert(undefined); // still undefined
'use strict';
undefined = 5; // throws TypeError
不所做的是创建自己的范围,mutable undefined
:
What you should not do is create your own scoped, mutable undefined
:
(function (undefined) {
// don't do this, because now `undefined` can be changed
undefined = 5;
})();
常数很好。仍然没必要,但很好。
Constant is fine. Still unnecessary, but fine.
(function () {
const undefined = void 0;
})();
这篇关于在JavaScript中,假设undefined没有被覆盖,它有多危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!