【问题标题】:how void operator exactly works in javascriptvoid 运算符在 javascript 中是如何工作的
【发布时间】:2023-01-14 00:25:47
【问题描述】:

作为一个定义空白运算符计算给定的表达式然后返回不明确的.

所以在这段代码中

void function test() {
  console.log('test function executed');
};

如果我们称它为测试(),那么 console.log('test function executed'); 是否应该先评估然后在完成返回 undefined 之后? ,而不是只返回undefined?像这个

void function iife() {
  console.log('iife is executed');
}();

【问题讨论】:

  • 它确实首先评估了这一点。
  • 已评估并不意味着函数本身正在运行,第二个函数仅由于函数声明后的()而运行(通常称为“自调用函数”之类的东西)
  • @technophyle 你能解释一下吗?
  • @DBS 那么在评价某事时我应该考虑什么? ,在第二个答案中,为什么它运行它而不是评估它并返回未定义
  • 不需要 void,例如在小书签中,你可以只做(function iife() { console.log('iife is executed'); })();

标签: javascript


【解决方案1】:

如果我们转到 operator precedence table,我们会看到函数调用 () 的优先级为 17,而 void 运算符的优先级仅为 14(与 typeofdelete 和 @ 相同987654326@)。正因为如此,下面的代码

void function iife() {
  console.log('iife is executed');
}();

实际上被当作

void (function iife() {
  console.log('iife is executed');
}());

如果您希望代码出错,那么您需要使用括号:

// Cannot call 'undefined' as a function
(void function iife() {
  console.log('iife is executed');
})();

【讨论】:

    【解决方案2】:

    这是两种不同的表达方式:

    • 创建函数
    • 另一个调用函数

    您可以看到 void 可以在此处正确创建函数:

    const x = function test() {
      console.log('test function executed');
    };
    
    console.log(x) // function

    无效:

    const x = void function test() {
      console.log('test function executed');
    };
    
    console.log(x) // undefined

    如果你希望函数调用返回undefined,那么在调用函数时必须使用void

    function test() {
      return 10
    }
    
    const x = void test()
    
    console.log(x)

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 1970-01-01
      • 2022-12-15
      • 2021-02-10
      • 2015-09-03
      • 1970-01-01
      相关资源
      最近更新 更多