当前位置:网站首页>JS中如何实现重载
JS中如何实现重载
2022-06-12 20:29:00 【站在桥上烤冷面】
什么是重载?
相同函数名,不同形参列表的多个函数,可以在调用时根据传入的实参值的不同,执行不同的逻辑。
好处:减少函数名的个数,减轻调用者的负担
如何实现呢?
在JS中是禁止两个同名函数同时存在的,如果同时存在,后面定义的函数会覆盖前面的函数,
可以借助arguments来解决。
什么是arguments?
函数中自带的,不需要自己定义,它是一个类数组对象。
什么是类数组?长得像数组,有下标,有length属性,也可以循环。不同的是数组是Array类型的对象,类数组是Object对象。类数组无权使用数组的方法
如何实现重载?
- 只定义一个函数,不需要任何参数
- 在函数内部,判断arguments的长度,元素值,元素类型等条件,根据传入实参值不同执行不同的逻辑
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function pay( ){ // arguments[ ].length // 0 1... if(arguments.length==0){ console.log(`手机支付...`) }else if(arguments.length==1){ console.log(`现金支付,收您${arguments[0]}元`) }else{ if(arguments[1]=="123456"){ console.log(`刷卡支付,从您卡号${arguments[0]}扣款成功!`) }else{ console.log(`刷卡支付,密码不正确`); } } } pay(); pay(100); pay("6553 1234","123456"); pay("6553 1234","12345"); </script> </body> </html> 运行结果: 手机支付... 现金支付,收您100元 刷卡支付,从您卡号6553 1234扣款成功! 刷卡支付,密码不正确
边栏推荐
- How can CTCM in the inspection lot system status of SAP QM be eliminated?
- How can the openwrt package manager image be switched to an alicloud source?
- P5076 【深基16.例7】普通二叉树(简化版)
- Detailed explanation of SQL exists usage
- Halcon angle and radian interchange
- 没有学历,自学软件测试,找到一份月入过万的测试工作真的有可能吗?
- Zhangqiming, vice director of the United Front Work Department of the CPC Anhui Provincial Committee, led a team to investigate the HoloNet Royal Hefei R & D base
- [games101] class note 8 - shading (shading frequency, graphics pipeline, texture mapping)
- Why my order by create_ Time ASC becomes order by ASC
- EditText控制从左上角开始
猜你喜欢

QT pro文件配置ffmpeg宏

Axure RP 9 for MAC (interactive product prototyping tool) Chinese version

Niuke.com: sum of three numbers

Detailed explanation of search tree and hash table

Illustrator tutorial, how to recolor artwork in illustrator?

测试人如何规划自己的未来?才能实现入行2年达到25k?

入行5年从10k的功能测试到年薪40w的测试开发,花7天时间整理的超全学习路线

How to determine fragment restored from Backstack

使用Swagger生成 API 文档(go语言示例)

Wechat jsapi payment pit summary
随机推荐
The joint empowerment plan of Baidu PaddlePaddle large enterprise open innovation center was launched! Help Pudong to upgrade its industry intelligently
Analysis of test questions in Chapter 13 of PMP preparation
A simple understanding of consistent hash
QT knowledge: QT widgets widget class [01]
Properties to YML
Continuously improve the overall performance of adaoracle Oracle Oracle
[leetcode 7 solution] integer inversion
Handwritten promise
6 R factor and judgment Na
Operating instructions for installing mysql5.7 in centos7
MySQL log
检测当前系统语言
Wall Street cheat sheet
SAP WM preliminary transaction code lx29 - list of fixed storage bins
[untitled]
go --- 监控文件变化
Deploy etcd cluster in static pod mode
一致性哈希的简单认识
View 的事件分发机制
JSP中的监听器