Skip to content

ES6 - Void 关键字

void 运算符是一个一元运算符 (unary operator),它评估给定的表达式 (expression),然后返回 undefined。它通常用于某些特定场景,在这些场景中,表达式需要执行其副作用 (side effect) 而不让其结果干扰,或者用于明确获取 undefined 原始值 (primitive value)。

语法 (Syntax):

void expression
// or
void(expression)

void 和立即执行函数表达式(IIFEs)

Section titled “void 和立即执行函数表达式(IIFEs)”

在历史上,void 有时被用来强制将 function 关键字视为表达式,以便实现 IIFE(Immediately Invoked Function Expression,立即执行函数表达式),尤其是在标准的括号写法 (function(){...})(); 不太常用或为了避免 JSLint 警告时。然而,这种用法在现代 JavaScript 中已经很少见了。

使用 void 的旧 IIFE 模式(现在较少用):

void function() {
const message = "IIFE executed using void!";
console.log(message);
}();
// Output: IIFE executed using void!

推荐使用现代 IIFE 模式:

(function() {
console.log("Standard IIFE.");
})();
(() => {
console.log("Arrow function IIFE.");
})();

在 ES 模块中,由于模块自身拥有作用域 (scoping),IIFE 用于作用域管理的需求已不那么必要了。

void 的一个常见用例是在 HTML <a> 标签的 href 属性中使用 javascript: URI。当执行 javascript: URI 时,浏览器通常会用表达式结果的字符串表示替换页面内容。如果结果是 undefined,则页面保持不变。void 0(或 void(0))是获取 undefined 的简洁方式。

使用 void 0 阻止导航:

<!-- Prevents navigation, alert is executed for its side effect -->
<a href="javascript:void(alert('Hello! Page will not change.'))">
Click Me (void example)
</a>
<br /><br />
<!-- Without void, if alert() returned something other than undefined,
the browser might try to display it. Alert itself returns undefined. -->
<a href="javascript:alert('Hello again!');">
Click Me (alert only)
</a>
<br /><br />
<!-- Common pattern to make a link do nothing on click by itself -->
<a href="javascript:void(0);" onclick="myJsFunction(); return false;">
Do something with JS (old pattern)
</a>

点击第一个链接时,alert 会弹出,但页面内容不会改变,因为 void 确保表达式评估为 undefined。第二个链接也有效,因为 alert() 本身就返回 undefined。

虽然 javascript:void(0); 可以工作,但通常最好使用更具语义化 (semantic) 的 HTML 和 JavaScript 进行事件处理 (event handling):

  • 对于不涉及导航的操作,使用 <button> 元素。
  • 如果使用 <a> 标签进行 JavaScript 操作,请在事件处理程序中使用 event.preventDefault(),并提供一个有意义的 href(例如 # 或备用 URL),以增强可访问性 (accessibility) 和 SEO。
  • 使用 JavaScript (element.addEventListener('click', handler);) 附加事件监听器,而不是使用行内 onclick 属性 (attribute)。
HTML:
```html
<a href="#" id="jsActionLink">Perform JS Action</a>
<button type="button" id="jsActionButton">Perform JS Action (Button)</button>

JavaScript:

document.getElementById('jsActionLink').addEventListener('click', function(event) {
event.preventDefault(); // Prevent navigation if href is not just "#"
console.log('Link clicked, action performed!');
// Perform your JavaScript action here
});
document.getElementById('jsActionButton').addEventListener('click', function() {
console.log('Button clicked, action performed!');
// Perform your JavaScript action here
});
总而言之,`void` 是一个特殊用途 (`niche`) 的运算符。其主要现代用途是在 `href` 属性中使用 `javascript:void(0)` 或 `javascript:void(expression)`,但即使是这种用法也有替代方案。理解它可以帮助阅读旧代码或处理特定场景。