vue3源码:为什么这么写const NOOP = () => { }; ????

vue3源码:为什么这么写const NOOP = () => { }; ????

vue3源码:为什么这么写const NOOP = () => { };
有的人说,方便判断、方便压缩???
为什么这么说???
有人能分别举例讲一讲吗?还有就是这么写还有其他的作用吗?
(一万个问号)
还有为什么不这样写?function NOOP(){}


回答:

如果写成 function NOOP(){},就有人问:
vue3源码里函数很多都用了箭头函数,为什么单独这里使用function声明??
为什么不写成const NOOP = () => { }??

就是个人习惯,你看其他函数声明几乎都是箭头函数:
const NO = () => false
const isString = val => typeof val === 'string'
const isOn = key => onRE.test(key)
因为这样写确实方便,更简洁易懂
但你不能整个文件几乎都是箭头函数,结果下面来一句function NOOP() {},就很迷惑

总结就是个人习惯,保持队形

就例如这个文件里 vue-next/packages/shared/src/domAttrConfig.ts

export function includeBooleanAttr(value) {

return !!value || value === ''

}

那为啥不用 const includeBooleanAttr = value => !!value || value === '' 呢,因为这代码就不是同一个人写的,不是尤大写的是其他维护成员后加的,人家就喜欢用function

你可以看一下其他文件,有的一个文件里都是用function声明,有的全都是箭头函数

在排除使用场景是否要this的情况,就是写法习惯的问题


回答:

在封装库的时候,很经常会把一些函数初始化为NOOP(空函数)。

简单举例,如:

Object.defineProperty(foo, key, {

configurable: true,

enumerable: true,

get: () => { /* ... */ },

set: NOOP

});

function bar(){ /* ... */ return NOOP }
  1. 方便判断:

    // 摘抄了 vue3 源码的小片段

    const get = isFunction(opt)

    ? opt.bind(publicThis, publicThis)

    : isFunction(opt.get)

    ? opt.get.bind(publicThis, publicThis)

    : NOOP;

    if (get === NOOP) {

    warn$1(`Computed property "${key}" has no getter.`);

    }

  2. 方便压缩:
    如果没有 NOOP 方法,那么在很多地方我们可能都要再定义一个匿名的空函数,这样的匿名函数就会导致无法被压缩,降低了代码的压缩率。
  3. 避免代码出错,当比如没有提供组件的 render 方法:

    const render = Component.render || NOOP;

    render();

    function NOOP(){} 和 const NOOP = () => {} 是一样的,不同写法而已。

补充:NOOP 也会提高代码的可读性。

以上是 vue3源码:为什么这么写const NOOP = () => { }; ???? 的全部内容, 来源链接: utcz.com/p/936610.html

回到顶部