关于前端:源码学习之noop

10次阅读

共计 1089 个字符,预计需要花费 3 分钟才能阅读完成。

/**
   * Perform no operation.
   * Stubbing args to make Flow happy without leaving useless transpiled code
   * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
   */
function noop(a, b, c) {}

这是一段 vue2 里的源码。

noop,是 No Operation 或 No Operation Performed 的缩写,意为无操作。

在汇编语言中,NOOP 指令通常用于管制时序的目标,强制内存对齐,避免流水线劫难,占据分支指令提早),或是作为占位符以供程序的改善(或代替被移除的指令)。

NOOP 在各种语言中的例子:

  • 在 C 语言中,分号(;)或空块({})都是 NOOP。
  • jQuery 中,“jQuery.noop()”函数会创立一个 NOOP。
  • 在 Perl 中,省略号(…)能够用作 NOOP。然而如果 Perl 尝试执行代码,则会给出未实现的异样。
  • 在 Python 中,“pass”语句可用作 NOOP。
  • 在 Visual Basic 中,分号(;)示意 NOOP。

在 vue 源码中的这个 noop 无操作空函数,次要作用就是为一些函数提供默认值,防止传入 undefined 之类的数据导致代码出错。

比方 vue 中:

    new Watcher(vm, updateComponent, noop, {before: function before() {if (vm._isMounted && !vm._isDestroyed) {callHook(vm, 'beforeUpdate');
        }
      }
    }, true /* isRenderWatcher */);

Watcher 具体实现为:

var Watcher = function Watcher(
    vm,
    expOrFn,
    cb,
    options,
    isRenderWatcher
) {...}

这里传入 noop 空函数的作用,就是防止在调用回调函数 cb 时,程序报错导致中断(比方传入 undefined,执行 cb 的时候就会报 cb is not a function 谬误)。

这里也能够间接应用一个无操作的匿名函数来代替 noop。在 vue2 的源码中,共有 20 处应用了 noop 函数,如果每次都创立一个匿名函数,一个是升高了代码的可读性,另一个是在 js 压缩时,这部分匿名函数是无奈被压缩的,升高了代码的压缩率。


参考资料:

  • NOP
  • No-operation instruction
  • noop in Javascript
  • What is the JavaScript convention for no operation?

正文完
 0