BING
斯是陋室,唯吾芳馨
衍生

JavaScript 中的 void 操作符

共 4,785 字,需阅读 12 分钟2017/06/29 下午3,553 次阅读

在 JavaScript 中,当我想取屋子里的第一条 dog 时,首先要判断 house 对象是否存在,然后再判断 house.dogs 是否存在,最后取 house.dogs[0]

在 JS 需要这么写:

          
  • 1
var dog = (typeof house !== 'undefined && house !== null) && house.dogs && house.dogs[0]

在 Coffee 中,我只需要这么写:

          
  • 1
dog = house?.dogs?[0];

Coffee 的本质就是 JS,之所以 Coffee 能工作的很好,是因为它生成出了高效而且健壮的 JS 代码,我们可以看看它的生成结果。

          
  • 1
  • 2
var dog, _ref; dog = typeof house !== "undefined" && house !== null ? (_ref = house.dogs) != null ? _ref[0] : void 0 : void 0;

短短一行 Coffee 代码生成出了如此长的 JS 代码,看上去似乎比我最前面自己用 JS 写的更靠谱更安全,末尾还出来了两个 void 0,这究竟是何方神圣?

结构化一下上面的例子:

          
  • 1
  • 2
  • 3
dog = (typeof house !== "undefined" && house !== null) ? ((_ref = house.dogs) != null ? _ref[0] : void 0 ) : void 0;

如果 house 未定义或 housenull 时,返回 void 0 如果 house.dogsnull 时,返回 void 0void 0 究竟是什么值,这个倒很容易测试:

          
  • 1
  • 2
typeof void 0 // 得到 "undefined" console.log(void 0) // 输出 undefined

似乎 void 0 就是 undefined 了,但这样子路数太野,也不够严谨,即无法回答:void 100; void hello(); void i++ 这无数可能组合的值是什么?

#规范是这么说的

在 ECMAScript 262 规范,有如下描述:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
The void Operator The production UnaryExpression : void UnaryExpression is evaluated as follows: - Let expr be the result of evaluating UnaryExpression. - Call GetValue(expr). - Return undefined. NOTE: GetValue must be called even though its value is not used because it may have observable side-effects.

搬译一下:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
void 操作符 产生式 UnaryExpression : void UnaryExpression 按如下流程解释: - 令 expr 为解释执行 UnaryExpression 的结果。 - 调用 GetValue(expr). - 返回 undefined. 注意:GetValue 一定要调用,即使它的值不会被用到,但是这个表达式可能会有副作用(side-effects)。

重点在于:无论 void 后的表达式是什么,void 操作符都会返回 undefined,因此上面由 Coffee 编译出来的代码我们可以认为是这样的:

          
  • 1
  • 2
  • 3
dog = (typeof house !== "undefined" && house !== null) ? ((_ref = house.dogs) != null ? _ref[0] : undefined ) : undefined ;

问题来了,既然 (void 0) === undefined,那直接写 undefined 不就行了么?

#为什么要用 void

因为 undefined 在 JavaScript 中不是保留字。换言之,你可以写出:

          
  • 1
  • 2
  • 3
  • 4
  • 5
function joke() { var undefined = "hello world"; console.log(undefined); // 会输出"hello world" } console.log(undefined); // 输出undefined

对的,你可以在一个函数上下文内以 undefined 做为变量名,于是在这个上下文写的代码便只能通过从全局作用域来取到 undefined,如:

          
  • 1
  • 2
window.undefined // 浏览器环境 GLOBAL.undefined // Node环境

但要注意的是,即便 window GLOBAL 仍然可以在函数上下文被定义,故从 window/GLOBAL 上取 undefined 并不是 100% 可靠的做法。如:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
function x() { var undefined = 'hello world', f = {}, window = { 'undefined': 'joke' }; console.log(undefined);// hello world console.log(window.undefined); //joke console.log(f.a === undefined); //false console.log(f.a === void 0); //true }

于是,采用 void 方式获取 undefined 便成了通用准则。如 underscore.js 里的 isUndefined 便是这么写的:

          
  • 1
  • 2
  • 3
_.isUndefined = function(obj) { return obj === void 0; }

除了采用 void 能保证取到 undefined 值以外,还有其它方法吗?有的,还有一种方式是通过函数调用。如 angular.js 的源码里就用这样的方式:

          
  • 1
  • 2
  • 3
(function(window, document, undefined) { //..... })(window, document);

通过不传参数,确保了 undefined 参数的值是一个 undefined

#其它作用

除了取 undefined 外,void 还有什么其它用处吗?

还有一个常见的功能,填充 href。下面是一个微博截图,它的转发、收藏、讨论都是超链接,但是用户并不希望点击它们会跳转到另一个页面,而是引发出一些交互操作。

理论上而言,这三个超链接都是没有 URL 的,但如果不写的话,呵呵,点击它会刷新整个页面。于是便用上了 href="javascript:void(0) 的方式,确保点击它会执行一个纯粹无聊的 void(0)

另一种情况是,如果我们要生成一个空的 srcimage,最好的方式似乎也是 src='javascript:void(0)',参见 StackOverflow 上的这个问题: What's the valid way to include an image with no src

#写在最后

回到 void 的定义,有一句话特别让人迷惑:

注意:GetValue 一定要调用,即使它的值不会被用到,但是这个表达式可能会有副作用(side-effects)。

这是什么意思?这表示无论 void 右边的表达式是什么,都要对其求值。这么说可能不太明白,在知乎上 winter 大神有过阐述关于 Js 中的 void,既然返回永远是 undefined,那么 GetValue 有啥用?,我且拾人牙慧,代入一个场景,看代码:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
var happiness = 10; var girl = { get whenMarry() { happiness--; return 1/0; // Infinity }, get happiness() { return happiness; } }; console.log(girl.whenMarry); // 调用了 whenMarry 的 get 方法 console.log(girl.happiness); // 9 void girl.whenMarry; // 调用了 whenMarry 的 get 方法 console.log(girl.happiness); // 8 delete girl.whenMarry; // 没有调用 whenMarry 的 get 方法 console.log(girl.happiness); // 还是8

上述代码定义了一个大龄文艺女青年,每被问到什么时候结婚呀(whenMarry),happiness 都会减1。 从执行情况可以看出,无论是普通访问 girl.whenMarry,还是 void girl.whenMarry 都会使她的 happiness--。 而如果把 void 换成 delete 操作符写成 delete girl.whenMarry,她的 happiness 就不会减了,因为 delete 操作符不会对 girl.whenMarry 求值。

#总结

void 有如下作用:

  • 通过采用 void 0undefined 比采用字面上的 undefined 更靠谱更安全,应该优先采用 void 0 这种方式。
  • 填充 <a>href 确保点击时不会产生页面跳转; 填充 <image>src,确保不会向服务器发出垃圾请求。

本文内容衍生自 《谈谈Javascript中的void操作符》

署名 - 非商业性使用 4.0 国际 https://surmon.me/article/61
1 / 1 条看法
访客身份
在下有一拙见,不知...
  • bour
    Bour🇩🇿DZSougueurLinuxChrome

    kjrlkzer

              
    • 1