no-void

禁止 void 运算符

void 运算符接受一个操作数并返回 undefinedvoid expression 将评估 expression 并返回 undefined。它可以用来忽略 expression 可能产生的任何副作用:

¥The void operator takes an operand and returns undefined: void expression will evaluate expression and return undefined. It can be used to ignore any side effects expression may produce:

使用 void 运算符的常见情况是获取 “pure” undefined 值,因为在 ES5 之前,undefined 变量是可变的:

¥The common case of using void operator is to get a “pure” undefined value as prior to ES5 the undefined variable was mutable:

// will always return undefined
(function(){
    return void 0;
})();

// will return 1 in ES3 and undefined in ES5+
(function(){
    undefined = 1;
    return undefined;
})();

// will throw TypeError in ES5+
(function(){
    'use strict';
    undefined = 1;
})();

另一种常见的情况是缩小代码,因为 void 0undefined 短:

¥Another common case is to minify code as void 0 is shorter than undefined:

foo = void 0;
foo = undefined;

当与 IIFE(立即调用的函数表达式)一起使用时,void 可用于强制将 function 关键字视为表达式而不是声明:

¥When used with IIFE (immediately-invoked function expression), void can be used to force the function keyword to be treated as an expression instead of a declaration:

var foo = 1;
void function(){ foo = 1; }() // will assign foo a value of 1
+function(){ foo = 1; }() // same as above
function(){ foo = 1; }() // will throw SyntaxError

某些代码样式禁止 void 运算符,将其标记为不明显且难以阅读。

¥Some code styles prohibit void operator, marking it as non-obvious and hard to read.

规则详情

¥Rule Details

此规则旨在消除使用 void 运算符。

¥This rule aims to eliminate use of void operator.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-void: "error"*/

void foo
void someFunction();

var foo = void bar();
function baz() {
    return void 0;
}

选项

¥Options

此规则有一个对象选项:

¥This rule has an object option:

  • allowAsStatement 设置为 true 允许将 void 运算符用作语句(默认 false)。

    ¥allowAsStatement set to true allows the void operator to be used as a statement (Default false).

allowAsStatement

allowAsStatement 设置为 true 时,规则不会在 void 运算符用作语句的情况下出错,即当它不用于表达式位置时,例如在变量赋值或函数返回中。

¥When allowAsStatement is set to true, the rule will not error on cases that the void operator is used as a statement, i.e. when it’s not used in an expression position, like in a variable assignment or a function return.

{ "allowAsStatement": true } 的错误代码示例:

¥Examples of incorrect code for { "allowAsStatement": true }:

在线运行
/*eslint no-void: ["error", { "allowAsStatement": true }]*/

var foo = void bar();
function baz() {
    return void 0;
}

{ "allowAsStatement": true } 的正确代码示例:

¥Examples of correct code for { "allowAsStatement": true }:

在线运行
/*eslint no-void: ["error", { "allowAsStatement": true }]*/

void foo;
void someFunction();

何时不使用

¥When Not To Use It

如果你有意使用 void 运算符,则可以禁用此规则。

¥If you intentionally use the void operator then you can disable this rule.

版本

此规则是在 ESLint v0.8.0 中引入。

进阶读物

资源

ESLint 中文网
粤ICP备13048890号