return void 0; vs return; [英] return void 0; vs return;

查看:60
本文介绍了return void 0; vs return;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Underscore.js的带注释的源代码。

I'm studying the annotated source code of Underscore.js.

http://underscorejs.org/docs/underscore.html#section-41

这是_.first方法:

Here's the _.first method:

  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n == null) || guard ? array[0] : slice.call(array, 0, n);
  };

问题:

为什么'return void 0;'而不只是'return;'?据我所知 return 隐式返回函数的undefined(值!)。就像'return void 0'那样。

Why 'return void 0;' and not just 'return;' ? As far as I know return implicitly returns undefined (the value!) from a function. Just like 'return void 0' does.

推荐答案

void操作符的MDN参考它声明:


void运算符通常仅用于获取未定义的
原始值,通常使用void(0)(相当于void
0)。在这些情况下,可以使用全局变量undefined来代替
(假设它尚未分配给非默认值)。

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

所以它确实相当于 undefined 但是 undefined 变量的问题在于它可以重新定义作为别的东西。就个人而言,我总是只需 return; 因为它始终产生完全相同的结果(如:(function(){})()=== void 0 )。

So it is indeed equivalent to undefined but the problem with the undefined variable is that it can be redefined as something else. Personally I would always simply return; because it consistently yields the exact same result (as in: (function() {})() === void 0).

由于一些评论者认为这不合适回答:

Since some commenter consider this not an appropriate answer:

(function(){})()=== void 0 总是得到true,这意味着它与 return; 完全相同。所以你可以认为这是Underscore库中的一个不一致,因为在其他地方使用普通的return语句(是的,即使它可能发生)。

(function() {})() === void 0 always yields true which means that it is exactly the same as return;. So you can consider this an inconsistency in the Underscore library as plain return statements are used in other places (yes, even there it can happen).

另一个附录,看起来好像它在缩小时也没有更好地优化。使用关闭编译器返回void 0; vs return; 以上代码示例的版本仍然大约增加5%。

Another addendum, it looks as if it also doesn't optimize any better during minification. Using the closure compiler the return void 0; vs return; version of the above code sample is still about 5% bigger.

这篇关于return void 0; vs return;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆