在很多源码中的 constant.js 文件中,会发现const UNDEFINED = void 0。
为什么不直接用 undefined 呢?
undefined 是全局对象的一个属性,初值就是基本数据类型 undefined,在 ES5 以来,它不可被配置,不可被修改。
但是,undefined 并不是一个保留字,因此在非全局作用域中,它是有可能作为一个变量被赋值的:
(function(undefined) {
console.log(undefined, typeof undefined)
})('foo')
// 打印 foo string
void 0 是什么?
void 是一个运算符,对给定的表达式进行求值,然后返回 undefined,永远返回 undefined。也可以加括号如 void(0)、 void(1)。
因此使用 void 0 代替直接使用 undefined,可以避免出 bug 等情况导致的 undefined 失真。







网友评论