我正在阅读这本名为 YDKJS 的书,其中提到:
typeof null
is an interesting case, because it errantly returns"object"
, when you'd expect it to return"null"
.Warning: This is a long-standing bug in JS, but one that is likely never going to be fixed. Too much code on the Web relies on the bug and thus fixing it would cause a lot more bugs!
我无法理解任何使用 null
返回类型的代码。任何人都可以提供一些示例用例吗?
最佳答案
并不是他们利用了null
的返回类型,而是变量的返回类型。
我的意思是,开发者写的案例有很多:
if (typeof something === "object"){
}
并且期望满足此条件的任何内容也都是null
。
所以他们依赖于这样一个事实,即 true
语句 block 中的任何内容都可以保存 null
值。
假设我们有这段代码:
switch (typeof something) {
case "object":
if (something) {
doSomethingWithObject(something);
} else {
rejectTransaction(); // we have null
}
break;
case "undefined":
throwAMeaningfulError();
break;
default:
doSomethingWithNumberOrString(something);
break;
}
可以看出,我们正在处理所有情况,无论是object
、undefined
、string
、number
或 null
。
如果此错误得到修复,并且 typeof null
将返回 null
,则永远不会调用 rejectTransaction
。相反,将调用 doSomethingWithNumberOrString
。
我并不是说这是一个很好的代码示例,但可能存在一些可能会破坏的代码,因为开发人员依赖于 typeof null
返回 "object"
而不是 "null"
关于javascript - 有哪些依赖于 'typeof null' 返回对象的代码示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50941493/