前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Thinking--函数参数重载

Thinking--函数参数重载

作者头像
奋飛
发布2020-05-28 17:03:28
4310
发布2020-05-28 17:03:28
举报
文章被收录于专栏:Super 前端Super 前端

Thinking系列,旨在利用10分钟的时间传达一种可落地的编程思想。

前段时间分享过 Thinking–函数参数Normalize思想在前端中的应用 ,对于函数多类型参数很是实用。

今天 ,阐述一种更小范围,业务中也更容易出现的场景 – “函数可接收数组或字符串,数组中每个元素的处理逻辑同字符串。”

实现

常规方式
代码语言:javascript
复制
function test (data : string | Array<string>): void {
  if (Array.isArray(data)) {
    for (let item of data) {
      _do(item)	// 直接调用处理逻辑
    }
  } else {
    _do(data)
  }
}

// 处理逻辑
function _do (params: string): void {
  console.log(params)
}

test('start')
test(['1', '2'])
递归方式
代码语言:javascript
复制
function test (data : string | Array<any>): void {
  if (Array.isArray(data)) {
    for (let item of data) {
      test(item) // 递归调用
    }
  } else {
    _do(data)
  }
}

// 处理逻辑
function _do (params: string): void {
  console.log(params)
}

test(['3', ['4', '5']])

这里使用递归的好处,data 可以是嵌套数组 ['3', ['4', '5']]

类似实现

https://github.com/vuejs/vue/blob/master/src/core/instance/events.js#L47

代码语言:javascript
复制
Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {
  const vm: Component = this
  if (Array.isArray(event)) {
    for (let i = 0, l = event.length; i < l; i++) {
      this.$on(event[i], fn)
    }
  } else {
    (vm._events[event] || (vm._events[event] = [])).push(fn)
    // optimize hook:event cost by using a boolean flag marked at registration
    // instead of a hash lookup
    if (hookRE.test(event)) {
      vm._hasHookEvent = true
    }
  }
  return vm
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现
    • 常规方式
      • 递归方式
      • 类似实现
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档